diff --git a/google/cloud/translate_v3/gapic_metadata.json b/google/cloud/translate_v3/gapic_metadata.json index 4480292f..b61ab661 100644 --- a/google/cloud/translate_v3/gapic_metadata.json +++ b/google/cloud/translate_v3/gapic_metadata.json @@ -116,6 +116,61 @@ ] } } + }, + "rest": { + "libraryClient": "TranslationServiceClient", + "rpcs": { + "BatchTranslateDocument": { + "methods": [ + "batch_translate_document" + ] + }, + "BatchTranslateText": { + "methods": [ + "batch_translate_text" + ] + }, + "CreateGlossary": { + "methods": [ + "create_glossary" + ] + }, + "DeleteGlossary": { + "methods": [ + "delete_glossary" + ] + }, + "DetectLanguage": { + "methods": [ + "detect_language" + ] + }, + "GetGlossary": { + "methods": [ + "get_glossary" + ] + }, + "GetSupportedLanguages": { + "methods": [ + "get_supported_languages" + ] + }, + "ListGlossaries": { + "methods": [ + "list_glossaries" + ] + }, + "TranslateDocument": { + "methods": [ + "translate_document" + ] + }, + "TranslateText": { + "methods": [ + "translate_text" + ] + } + } } } } diff --git a/google/cloud/translate_v3/services/translation_service/async_client.py b/google/cloud/translate_v3/services/translation_service/async_client.py index 07747143..67df2ed1 100644 --- a/google/cloud/translate_v3/services/translation_service/async_client.py +++ b/google/cloud/translate_v3/services/translation_service/async_client.py @@ -287,10 +287,10 @@ async def sample_translate_text(): on the ``request`` instance; if ``request`` is provided, this should not be set. target_language_code (:class:`str`): - Required. The BCP-47 language code to - use for translation of the input text, - set to one of the language codes listed - in Language Support. + Required. The ISO-639 language code + to use for translation of the input + text, set to one of the language codes + listed in Language Support. This corresponds to the ``target_language_code`` field on the ``request`` instance; if ``request`` is provided, this @@ -298,8 +298,8 @@ async def sample_translate_text(): contents (:class:`MutableSequence[str]`): Required. The content of the input in string format. We recommend the total - content be less than 30k codepoints. The - max length of this field is 1024. + content be less than 30,000 codepoints. + The max length of this field is 1024. Use BatchTranslateText for larger text. This corresponds to the ``contents`` field @@ -337,8 +337,8 @@ async def sample_translate_text(): on the ``request`` instance; if ``request`` is provided, this should not be set. source_language_code (:class:`str`): - Optional. The BCP-47 language code of - the input text if known, for example, + Optional. The ISO-639 language code + of the input text if known, for example, "en-US" or "sr-Latn". Supported language codes are listed in Language Support. If the source language isn't specified, the @@ -1027,19 +1027,17 @@ async def sample_batch_translate_document(): on the ``request`` instance; if ``request`` is provided, this should not be set. source_language_code (:class:`str`): - Required. The BCP-47 language code of - the input document if known, for - example, "en-US" or "sr-Latn". Supported - language codes are listed in Language - Support - (https://cloud.google.com/translate/docs/languages). + Required. The ISO-639 language code of the input + document if known, for example, "en-US" or "sr-Latn". + Supported language codes are listed in `Language + Support `__. This corresponds to the ``source_language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. target_language_codes (:class:`MutableSequence[str]`): - Required. The BCP-47 language code to - use for translation of the input + Required. The ISO-639 language code + to use for translation of the input document. Specify up to 10 language codes here. @@ -1223,7 +1221,7 @@ async def sample_create_glossary(): The result type for the operation will be :class:`google.cloud.translate_v3.types.Glossary` - Represents a glossary built from user provided data. + Represents a glossary built from user-provided data. """ # Create or coerce a protobuf request object. @@ -1461,8 +1459,8 @@ async def sample_get_glossary(): Returns: google.cloud.translate_v3.types.Glossary: - Represents a glossary built from user - provided data. + Represents a glossary built from + user-provided data. """ # Create or coerce a protobuf request object. diff --git a/google/cloud/translate_v3/services/translation_service/client.py b/google/cloud/translate_v3/services/translation_service/client.py index b2adf508..406237b8 100644 --- a/google/cloud/translate_v3/services/translation_service/client.py +++ b/google/cloud/translate_v3/services/translation_service/client.py @@ -54,6 +54,7 @@ from .transports.base import TranslationServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import TranslationServiceGrpcTransport from .transports.grpc_asyncio import TranslationServiceGrpcAsyncIOTransport +from .transports.rest import TranslationServiceRestTransport class TranslationServiceClientMeta(type): @@ -69,6 +70,7 @@ class TranslationServiceClientMeta(type): ) # type: Dict[str, Type[TranslationServiceTransport]] _transport_registry["grpc"] = TranslationServiceGrpcTransport _transport_registry["grpc_asyncio"] = TranslationServiceGrpcAsyncIOTransport + _transport_registry["rest"] = TranslationServiceRestTransport def get_transport_class( cls, @@ -513,10 +515,10 @@ def sample_translate_text(): on the ``request`` instance; if ``request`` is provided, this should not be set. target_language_code (str): - Required. The BCP-47 language code to - use for translation of the input text, - set to one of the language codes listed - in Language Support. + Required. The ISO-639 language code + to use for translation of the input + text, set to one of the language codes + listed in Language Support. This corresponds to the ``target_language_code`` field on the ``request`` instance; if ``request`` is provided, this @@ -524,8 +526,8 @@ def sample_translate_text(): contents (MutableSequence[str]): Required. The content of the input in string format. We recommend the total - content be less than 30k codepoints. The - max length of this field is 1024. + content be less than 30,000 codepoints. + The max length of this field is 1024. Use BatchTranslateText for larger text. This corresponds to the ``contents`` field @@ -563,8 +565,8 @@ def sample_translate_text(): on the ``request`` instance; if ``request`` is provided, this should not be set. source_language_code (str): - Optional. The BCP-47 language code of - the input text if known, for example, + Optional. The ISO-639 language code + of the input text if known, for example, "en-US" or "sr-Latn". Supported language codes are listed in Language Support. If the source language isn't specified, the @@ -1245,19 +1247,17 @@ def sample_batch_translate_document(): on the ``request`` instance; if ``request`` is provided, this should not be set. source_language_code (str): - Required. The BCP-47 language code of - the input document if known, for - example, "en-US" or "sr-Latn". Supported - language codes are listed in Language - Support - (https://cloud.google.com/translate/docs/languages). + Required. The ISO-639 language code of the input + document if known, for example, "en-US" or "sr-Latn". + Supported language codes are listed in `Language + Support `__. This corresponds to the ``source_language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. target_language_codes (MutableSequence[str]): - Required. The BCP-47 language code to - use for translation of the input + Required. The ISO-639 language code + to use for translation of the input document. Specify up to 10 language codes here. @@ -1441,7 +1441,7 @@ def sample_create_glossary(): The result type for the operation will be :class:`google.cloud.translate_v3.types.Glossary` - Represents a glossary built from user provided data. + Represents a glossary built from user-provided data. """ # Create or coerce a protobuf request object. @@ -1669,8 +1669,8 @@ def sample_get_glossary(): Returns: google.cloud.translate_v3.types.Glossary: - Represents a glossary built from user - provided data. + Represents a glossary built from + user-provided data. """ # Create or coerce a protobuf request object. diff --git a/google/cloud/translate_v3/services/translation_service/transports/__init__.py b/google/cloud/translate_v3/services/translation_service/transports/__init__.py index 32fa3072..883dedb0 100644 --- a/google/cloud/translate_v3/services/translation_service/transports/__init__.py +++ b/google/cloud/translate_v3/services/translation_service/transports/__init__.py @@ -19,6 +19,8 @@ from .base import TranslationServiceTransport from .grpc import TranslationServiceGrpcTransport from .grpc_asyncio import TranslationServiceGrpcAsyncIOTransport +from .rest import TranslationServiceRestTransport +from .rest import TranslationServiceRestInterceptor # Compile a registry of transports. @@ -27,9 +29,12 @@ ) # type: Dict[str, Type[TranslationServiceTransport]] _transport_registry["grpc"] = TranslationServiceGrpcTransport _transport_registry["grpc_asyncio"] = TranslationServiceGrpcAsyncIOTransport +_transport_registry["rest"] = TranslationServiceRestTransport __all__ = ( "TranslationServiceTransport", "TranslationServiceGrpcTransport", "TranslationServiceGrpcAsyncIOTransport", + "TranslationServiceRestTransport", + "TranslationServiceRestInterceptor", ) diff --git a/google/cloud/translate_v3/services/translation_service/transports/rest.py b/google/cloud/translate_v3/services/translation_service/transports/rest.py new file mode 100644 index 00000000..cfca7970 --- /dev/null +++ b/google/cloud/translate_v3/services/translation_service/transports/rest.py @@ -0,0 +1,1621 @@ +# -*- 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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.translate_v3.types import translation_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import ( + TranslationServiceTransport, + DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO, +) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class TranslationServiceRestInterceptor: + """Interceptor for TranslationService. + + 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 TranslationServiceRestTransport. + + .. code-block:: python + class MyCustomTranslationServiceInterceptor(TranslationServiceRestInterceptor): + def pre_batch_translate_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_translate_document(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_translate_text(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_translate_text(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_glossary(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_glossary(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_glossary(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_glossary(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_detect_language(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_detect_language(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_glossary(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_glossary(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_supported_languages(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_supported_languages(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_glossaries(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_glossaries(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_translate_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_translate_document(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_translate_text(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_translate_text(self, response): + logging.log(f"Received response: {response}") + return response + + transport = TranslationServiceRestTransport(interceptor=MyCustomTranslationServiceInterceptor()) + client = TranslationServiceClient(transport=transport) + + + """ + + def pre_batch_translate_document( + self, + request: translation_service.BatchTranslateDocumentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + translation_service.BatchTranslateDocumentRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for batch_translate_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_batch_translate_document( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for batch_translate_document + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + def pre_batch_translate_text( + self, + request: translation_service.BatchTranslateTextRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + translation_service.BatchTranslateTextRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for batch_translate_text + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_batch_translate_text( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for batch_translate_text + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + def pre_create_glossary( + self, + request: translation_service.CreateGlossaryRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[translation_service.CreateGlossaryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_glossary + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_create_glossary( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_glossary + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + def pre_delete_glossary( + self, + request: translation_service.DeleteGlossaryRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[translation_service.DeleteGlossaryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_glossary + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_delete_glossary( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_glossary + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + def pre_detect_language( + self, + request: translation_service.DetectLanguageRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[translation_service.DetectLanguageRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for detect_language + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_detect_language( + self, response: translation_service.DetectLanguageResponse + ) -> translation_service.DetectLanguageResponse: + """Post-rpc interceptor for detect_language + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + def pre_get_glossary( + self, + request: translation_service.GetGlossaryRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[translation_service.GetGlossaryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_glossary + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_get_glossary( + self, response: translation_service.Glossary + ) -> translation_service.Glossary: + """Post-rpc interceptor for get_glossary + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + def pre_get_supported_languages( + self, + request: translation_service.GetSupportedLanguagesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + translation_service.GetSupportedLanguagesRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for get_supported_languages + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_get_supported_languages( + self, response: translation_service.SupportedLanguages + ) -> translation_service.SupportedLanguages: + """Post-rpc interceptor for get_supported_languages + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + def pre_list_glossaries( + self, + request: translation_service.ListGlossariesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[translation_service.ListGlossariesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_glossaries + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_list_glossaries( + self, response: translation_service.ListGlossariesResponse + ) -> translation_service.ListGlossariesResponse: + """Post-rpc interceptor for list_glossaries + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + def pre_translate_document( + self, + request: translation_service.TranslateDocumentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[translation_service.TranslateDocumentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for translate_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_translate_document( + self, response: translation_service.TranslateDocumentResponse + ) -> translation_service.TranslateDocumentResponse: + """Post-rpc interceptor for translate_document + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + def pre_translate_text( + self, + request: translation_service.TranslateTextRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[translation_service.TranslateTextRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for translate_text + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_translate_text( + self, response: translation_service.TranslateTextResponse + ) -> translation_service.TranslateTextResponse: + """Post-rpc interceptor for translate_text + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class TranslationServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: TranslationServiceRestInterceptor + + +class TranslationServiceRestTransport(TranslationServiceTransport): + """REST backend transport for TranslationService. + + Provides natural language translation operations. + + 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 = "translate.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[TranslationServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or TranslationServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v3/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v3/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*}/operations", + }, + ], + "google.longrunning.Operations.WaitOperation": [ + { + "method": "post", + "uri": "/v3/{name=projects/*/locations/*/operations/*}:wait", + "body": "*", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v3", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _BatchTranslateDocument(TranslationServiceRestStub): + def __hash__(self): + return hash("BatchTranslateDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.BatchTranslateDocumentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the batch translate document method over HTTP. + + Args: + request (~.translation_service.BatchTranslateDocumentRequest): + The request object. The BatchTranslateDocument request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{parent=projects/*/locations/*}:batchTranslateDocument", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_batch_translate_document( + request, metadata + ) + pb_request = translation_service.BatchTranslateDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_translate_document(resp) + return resp + + class _BatchTranslateText(TranslationServiceRestStub): + def __hash__(self): + return hash("BatchTranslateText") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.BatchTranslateTextRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the batch translate text method over HTTP. + + Args: + request (~.translation_service.BatchTranslateTextRequest): + The request object. The batch translation request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{parent=projects/*/locations/*}:batchTranslateText", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_batch_translate_text( + request, metadata + ) + pb_request = translation_service.BatchTranslateTextRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_translate_text(resp) + return resp + + class _CreateGlossary(TranslationServiceRestStub): + def __hash__(self): + return hash("CreateGlossary") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.CreateGlossaryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create glossary method over HTTP. + + Args: + request (~.translation_service.CreateGlossaryRequest): + The request object. Request message for CreateGlossary. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{parent=projects/*/locations/*}/glossaries", + "body": "glossary", + }, + ] + request, metadata = self._interceptor.pre_create_glossary(request, metadata) + pb_request = translation_service.CreateGlossaryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_glossary(resp) + return resp + + class _DeleteGlossary(TranslationServiceRestStub): + def __hash__(self): + return hash("DeleteGlossary") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.DeleteGlossaryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete glossary method over HTTP. + + Args: + request (~.translation_service.DeleteGlossaryRequest): + The request object. Request message for DeleteGlossary. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v3/{name=projects/*/locations/*/glossaries/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_glossary(request, metadata) + pb_request = translation_service.DeleteGlossaryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_glossary(resp) + return resp + + class _DetectLanguage(TranslationServiceRestStub): + def __hash__(self): + return hash("DetectLanguage") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.DetectLanguageRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.DetectLanguageResponse: + r"""Call the detect language method over HTTP. + + Args: + request (~.translation_service.DetectLanguageRequest): + The request object. The request message for language + detection. + + 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: + ~.translation_service.DetectLanguageResponse: + The response message for language + detection. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{parent=projects/*/locations/*}:detectLanguage", + "body": "*", + }, + { + "method": "post", + "uri": "/v3/{parent=projects/*}:detectLanguage", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_detect_language(request, metadata) + pb_request = translation_service.DetectLanguageRequest.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 = translation_service.DetectLanguageResponse() + pb_resp = translation_service.DetectLanguageResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_detect_language(resp) + return resp + + class _GetGlossary(TranslationServiceRestStub): + def __hash__(self): + return hash("GetGlossary") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.GetGlossaryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.Glossary: + r"""Call the get glossary method over HTTP. + + Args: + request (~.translation_service.GetGlossaryRequest): + The request object. Request message for GetGlossary. + 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: + ~.translation_service.Glossary: + Represents a glossary built from + user-provided data. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*/glossaries/*}", + }, + ] + request, metadata = self._interceptor.pre_get_glossary(request, metadata) + pb_request = translation_service.GetGlossaryRequest.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 = translation_service.Glossary() + pb_resp = translation_service.Glossary.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_glossary(resp) + return resp + + class _GetSupportedLanguages(TranslationServiceRestStub): + def __hash__(self): + return hash("GetSupportedLanguages") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.GetSupportedLanguagesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.SupportedLanguages: + r"""Call the get supported languages method over HTTP. + + Args: + request (~.translation_service.GetSupportedLanguagesRequest): + The request object. The request message for discovering + supported languages. + + 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: + ~.translation_service.SupportedLanguages: + The response message for discovering + supported languages. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{parent=projects/*/locations/*}/supportedLanguages", + }, + { + "method": "get", + "uri": "/v3/{parent=projects/*}/supportedLanguages", + }, + ] + request, metadata = self._interceptor.pre_get_supported_languages( + request, metadata + ) + pb_request = translation_service.GetSupportedLanguagesRequest.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 = translation_service.SupportedLanguages() + pb_resp = translation_service.SupportedLanguages.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_supported_languages(resp) + return resp + + class _ListGlossaries(TranslationServiceRestStub): + def __hash__(self): + return hash("ListGlossaries") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.ListGlossariesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.ListGlossariesResponse: + r"""Call the list glossaries method over HTTP. + + Args: + request (~.translation_service.ListGlossariesRequest): + The request object. Request message for ListGlossaries. + 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: + ~.translation_service.ListGlossariesResponse: + Response message for ListGlossaries. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{parent=projects/*/locations/*}/glossaries", + }, + ] + request, metadata = self._interceptor.pre_list_glossaries(request, metadata) + pb_request = translation_service.ListGlossariesRequest.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 = translation_service.ListGlossariesResponse() + pb_resp = translation_service.ListGlossariesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_glossaries(resp) + return resp + + class _TranslateDocument(TranslationServiceRestStub): + def __hash__(self): + return hash("TranslateDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.TranslateDocumentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.TranslateDocumentResponse: + r"""Call the translate document method over HTTP. + + Args: + request (~.translation_service.TranslateDocumentRequest): + The request object. A document translation request. + 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: + ~.translation_service.TranslateDocumentResponse: + A translated document response + message. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{parent=projects/*/locations/*}:translateDocument", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_translate_document( + request, metadata + ) + pb_request = translation_service.TranslateDocumentRequest.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 = translation_service.TranslateDocumentResponse() + pb_resp = translation_service.TranslateDocumentResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_translate_document(resp) + return resp + + class _TranslateText(TranslationServiceRestStub): + def __hash__(self): + return hash("TranslateText") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.TranslateTextRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.TranslateTextResponse: + r"""Call the translate text method over HTTP. + + Args: + request (~.translation_service.TranslateTextRequest): + The request object. The request message for synchronous + translation. + + 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: + ~.translation_service.TranslateTextResponse: + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{parent=projects/*/locations/*}:translateText", + "body": "*", + }, + { + "method": "post", + "uri": "/v3/{parent=projects/*}:translateText", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_translate_text(request, metadata) + pb_request = translation_service.TranslateTextRequest.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 = translation_service.TranslateTextResponse() + pb_resp = translation_service.TranslateTextResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_translate_text(resp) + return resp + + @property + def batch_translate_document( + self, + ) -> Callable[ + [translation_service.BatchTranslateDocumentRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchTranslateDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_translate_text( + self, + ) -> Callable[ + [translation_service.BatchTranslateTextRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchTranslateText(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_glossary( + self, + ) -> Callable[ + [translation_service.CreateGlossaryRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateGlossary(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_glossary( + self, + ) -> Callable[ + [translation_service.DeleteGlossaryRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteGlossary(self._session, self._host, self._interceptor) # type: ignore + + @property + def detect_language( + self, + ) -> Callable[ + [translation_service.DetectLanguageRequest], + translation_service.DetectLanguageResponse, + ]: + # 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._DetectLanguage(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_glossary( + self, + ) -> Callable[ + [translation_service.GetGlossaryRequest], translation_service.Glossary + ]: + # 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._GetGlossary(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_supported_languages( + self, + ) -> Callable[ + [translation_service.GetSupportedLanguagesRequest], + translation_service.SupportedLanguages, + ]: + # 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._GetSupportedLanguages(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_glossaries( + self, + ) -> Callable[ + [translation_service.ListGlossariesRequest], + translation_service.ListGlossariesResponse, + ]: + # 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._ListGlossaries(self._session, self._host, self._interceptor) # type: ignore + + @property + def translate_document( + self, + ) -> Callable[ + [translation_service.TranslateDocumentRequest], + translation_service.TranslateDocumentResponse, + ]: + # 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._TranslateDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def translate_text( + self, + ) -> Callable[ + [translation_service.TranslateTextRequest], + translation_service.TranslateTextResponse, + ]: + # 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._TranslateText(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("TranslationServiceRestTransport",) diff --git a/google/cloud/translate_v3/types/translation_service.py b/google/cloud/translate_v3/types/translation_service.py index 742a86bd..867959ce 100644 --- a/google/cloud/translate_v3/types/translation_service.py +++ b/google/cloud/translate_v3/types/translation_service.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence import proto # type: ignore @@ -73,14 +75,13 @@ class TranslateTextGlossaryConfig(proto.Message): Required. The ``glossary`` to be applied for this translation. - The format depends on glossary: + The format depends on the glossary: - - User provided custom glossary: + - User-provided custom glossary: ``projects/{project-number-or-id}/locations/{location-id}/glossaries/{glossary-id}`` ignore_case (bool): - Optional. Indicates match is - case-insensitive. Default value is false if - missing. + Optional. Indicates match is case insensitive. The default + value is ``false`` if missing. """ glossary: str = proto.Field( @@ -100,15 +101,15 @@ class TranslateTextRequest(proto.Message): contents (MutableSequence[str]): Required. The content of the input in string format. We recommend the total content be less - than 30k codepoints. The max length of this - field is 1024. - Use BatchTranslateText for larger text. + than 30,000 codepoints. The max length of this + field is 1024. Use BatchTranslateText for larger + text. mime_type (str): Optional. The format of the source text, for example, "text/html", "text/plain". If left blank, the MIME type defaults to "text/html". source_language_code (str): - Optional. The BCP-47 language code of the + Optional. The ISO-639 language code of the input text if known, for example, "en-US" or "sr-Latn". Supported language codes are listed in Language Support. If the source language @@ -116,9 +117,9 @@ class TranslateTextRequest(proto.Message): the source language automatically and returns the source language within the response. target_language_code (str): - Required. The BCP-47 language code to use for - translation of the input text, set to one of the - language codes listed in Language Support. + Required. The ISO-639 language code to use + for translation of the input text, set to one of + the language codes listed in Language Support. parent (str): Required. Project or location to make a call. Must refer to a caller's project. @@ -254,7 +255,7 @@ class Translation(proto.Message): then ``model`` here would be normalized to ``projects/{project-number}/locations/{location-id}/models/general/nmt``. detected_language_code (str): - The BCP-47 language code of source text in + The ISO-639 language code of source text in the initial request, detected automatically, if no source language was passed within the initial request. If the source language was passed, @@ -365,8 +366,8 @@ class DetectedLanguage(proto.Message): Attributes: language_code (str): - The BCP-47 language code of source content in - the request, detected automatically. + The ISO-639 language code of the source + content in the request, detected automatically. confidence (float): The confidence of the detection result for this language. @@ -480,17 +481,17 @@ class SupportedLanguage(proto.Message): language_code (str): Supported language code, generally consisting of its ISO 639-1 identifier, for example, 'en', - 'ja'. In certain cases, BCP-47 codes including + 'ja'. In certain cases, ISO-639 codes including language and region identifiers are returned - (for example, 'zh-TW' and 'zh-CN') + (for example, 'zh-TW' and 'zh-CN'). display_name (str): - Human readable name of the language localized + Human-readable name of the language localized in the display language specified in the request. support_source (bool): - Can be used as source language. + Can be used as a source language. support_target (bool): - Can be used as target language. + Can be used as a target language. """ language_code: str = proto.Field( @@ -637,7 +638,7 @@ class OutputConfig(proto.Message): Since index.csv will be keeping updated during the process, please make sure there is no custom retention policy applied on the output bucket that may avoid file updating. - (https://cloud.google.com/storage/docs/bucket-lock?hl=en#retention-policy) + (https://cloud.google.com/storage/docs/bucket-lock#retention-policy) The format of translations_file (for target language code 'trg') is: @@ -842,7 +843,7 @@ class TranslateDocumentRequest(proto.Message): the same location-id), otherwise an INVALID_ARGUMENT (400) error is returned. source_language_code (str): - Optional. The BCP-47 language code of the + Optional. The ISO-639 language code of the input document if known, for example, "en-US" or "sr-Latn". Supported language codes are listed in Language Support. If the source language @@ -852,9 +853,10 @@ class TranslateDocumentRequest(proto.Message): language must be specified if the request contains a glossary or a custom model. target_language_code (str): - Required. The BCP-47 language code to use for - translation of the input document, set to one of - the language codes listed in Language Support. + Required. The ISO-639 language code to use + for translation of the input document, set to + one of the language codes listed in Language + Support. document_input_config (google.cloud.translate_v3.types.DocumentInputConfig): Required. Input configurations. document_output_config (google.cloud.translate_v3.types.DocumentOutputConfig): @@ -895,6 +897,21 @@ class TranslateDocumentRequest(proto.Message): See https://cloud.google.com/translate/docs/advanced/labels for more information. + customized_attribution (str): + Optional. This flag is to support user customized + attribution. If not provided, the default is + ``Machine Translated by Google``. Customized attribution + should follow rules in + https://cloud.google.com/translate/attribution#attribution_and_logos + is_translate_native_pdf_only (bool): + Optional. If true, the page limit of online + native pdf translation is 300 and only native + pdf pages will be translated. + enable_shadow_removal_native_pdf (bool): + Optional. If true, use the text removal to remove the shadow + text on background image for native pdf translation. Shadow + removal feature can only be enabled when + is_translate_native_pdf_only is false """ parent: str = proto.Field( @@ -933,6 +950,18 @@ class TranslateDocumentRequest(proto.Message): proto.STRING, number=8, ) + customized_attribution: str = proto.Field( + proto.STRING, + number=10, + ) + is_translate_native_pdf_only: bool = proto.Field( + proto.BOOL, + number=11, + ) + enable_shadow_removal_native_pdf: bool = proto.Field( + proto.BOOL, + number=12, + ) class DocumentTranslation(proto.Message): @@ -1262,11 +1291,10 @@ class GlossaryInputConfig(proto.Message): For unidirectional glossaries: - - TSV/CSV (``.tsv``/``.csv``): 2 column file, tab- or + - TSV/CSV (``.tsv``/``.csv``): Two column file, tab- or comma-separated. The first column is source text. The - second column is target text. The file must not contain - headers. That is, the first row is data, not column - names. + second column is target text. No headers in this file. + The first row contains data and not column names. - TMX (``.tmx``): TMX file with parallel data defining source/target term pairs. @@ -1290,7 +1318,7 @@ class GlossaryInputConfig(proto.Message): class Glossary(proto.Message): - r"""Represents a glossary built from user provided data. + r"""Represents a glossary built from user-provided data. This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -1324,6 +1352,8 @@ class Glossary(proto.Message): end_time (google.protobuf.timestamp_pb2.Timestamp): Output only. When the glossary creation was finished. + display_name (str): + Optional. The display name of the glossary. """ class LanguageCodePair(proto.Message): @@ -1331,11 +1361,11 @@ class LanguageCodePair(proto.Message): Attributes: source_language_code (str): - Required. The BCP-47 language code of the input text, for + Required. The ISO-639 language code of the input text, for example, "en-US". Expected to be an exact match for GlossaryTerm.language_code. target_language_code (str): - Required. The BCP-47 language code for translation output, + Required. The ISO-639 language code for translation output, for example, "zh-CN". Expected to be an exact match for GlossaryTerm.language_code. """ @@ -1354,7 +1384,7 @@ class LanguageCodesSet(proto.Message): Attributes: language_codes (MutableSequence[str]): - The BCP-47 language code(s) for terms defined in the + The ISO-639 language code(s) for terms defined in the glossary. All entries are unique. The list contains at least two entries. Expected to be an exact match for GlossaryTerm.language_code. @@ -1400,6 +1430,10 @@ class LanguageCodesSet(proto.Message): number=8, message=timestamp_pb2.Timestamp, ) + display_name: str = proto.Field( + proto.STRING, + number=9, + ) class CreateGlossaryRequest(proto.Message): @@ -1717,15 +1751,14 @@ class BatchTranslateDocumentRequest(proto.Message): region (have the same location-id) can be used, otherwise an INVALID_ARGUMENT (400) error is returned. source_language_code (str): - Required. The BCP-47 language code of the - input document if known, for example, "en-US" or - "sr-Latn". Supported language codes are listed - in Language Support - (https://cloud.google.com/translate/docs/languages). + Required. The ISO-639 language code of the input document if + known, for example, "en-US" or "sr-Latn". Supported language + codes are listed in `Language + Support `__. target_language_codes (MutableSequence[str]): - Required. The BCP-47 language code to use for - translation of the input document. Specify up to - 10 language codes here. + Required. The ISO-639 language code to use + for translation of the input document. Specify + up to 10 language codes here. input_configs (MutableSequence[google.cloud.translate_v3.types.BatchDocumentInputConfig]): Required. Input configurations. The total number of files matched should be <= @@ -1768,6 +1801,12 @@ class BatchTranslateDocumentRequest(proto.Message): If nothing specified, output files will be in the same format as the original file. + customized_attribution (str): + Optional. This flag is to support user customized + attribution. If not provided, the default is + ``Machine Translated by Google``. Customized attribution + should follow rules in + https://cloud.google.com/translate/attribution#attribution_and_logos """ parent: str = proto.Field( @@ -1808,6 +1847,10 @@ class BatchTranslateDocumentRequest(proto.Message): proto.STRING, number=8, ) + customized_attribution: str = proto.Field( + proto.STRING, + number=10, + ) class BatchDocumentInputConfig(proto.Message): @@ -1892,7 +1935,7 @@ class BatchDocumentOutputConfig(proto.Message): Since index.csv will be keeping updated during the process, please make sure there is no custom retention policy applied on the output bucket that may avoid file updating. - (https://cloud.google.com/storage/docs/bucket-lock?hl=en#retention-policy) + (https://cloud.google.com/storage/docs/bucket-lock#retention-policy) The naming format of translation output files follows (for target language code [trg]): ``translation_output``: diff --git a/google/cloud/translate_v3beta1/gapic_metadata.json b/google/cloud/translate_v3beta1/gapic_metadata.json index f3ed7241..8ad815f3 100644 --- a/google/cloud/translate_v3beta1/gapic_metadata.json +++ b/google/cloud/translate_v3beta1/gapic_metadata.json @@ -116,6 +116,61 @@ ] } } + }, + "rest": { + "libraryClient": "TranslationServiceClient", + "rpcs": { + "BatchTranslateDocument": { + "methods": [ + "batch_translate_document" + ] + }, + "BatchTranslateText": { + "methods": [ + "batch_translate_text" + ] + }, + "CreateGlossary": { + "methods": [ + "create_glossary" + ] + }, + "DeleteGlossary": { + "methods": [ + "delete_glossary" + ] + }, + "DetectLanguage": { + "methods": [ + "detect_language" + ] + }, + "GetGlossary": { + "methods": [ + "get_glossary" + ] + }, + "GetSupportedLanguages": { + "methods": [ + "get_supported_languages" + ] + }, + "ListGlossaries": { + "methods": [ + "list_glossaries" + ] + }, + "TranslateDocument": { + "methods": [ + "translate_document" + ] + }, + "TranslateText": { + "methods": [ + "translate_text" + ] + } + } } } } diff --git a/google/cloud/translate_v3beta1/services/translation_service/client.py b/google/cloud/translate_v3beta1/services/translation_service/client.py index 9125b32e..35e64c5e 100644 --- a/google/cloud/translate_v3beta1/services/translation_service/client.py +++ b/google/cloud/translate_v3beta1/services/translation_service/client.py @@ -54,6 +54,7 @@ from .transports.base import TranslationServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import TranslationServiceGrpcTransport from .transports.grpc_asyncio import TranslationServiceGrpcAsyncIOTransport +from .transports.rest import TranslationServiceRestTransport class TranslationServiceClientMeta(type): @@ -69,6 +70,7 @@ class TranslationServiceClientMeta(type): ) # type: Dict[str, Type[TranslationServiceTransport]] _transport_registry["grpc"] = TranslationServiceGrpcTransport _transport_registry["grpc_asyncio"] = TranslationServiceGrpcAsyncIOTransport + _transport_registry["rest"] = TranslationServiceRestTransport def get_transport_class( cls, diff --git a/google/cloud/translate_v3beta1/services/translation_service/transports/__init__.py b/google/cloud/translate_v3beta1/services/translation_service/transports/__init__.py index 32fa3072..883dedb0 100644 --- a/google/cloud/translate_v3beta1/services/translation_service/transports/__init__.py +++ b/google/cloud/translate_v3beta1/services/translation_service/transports/__init__.py @@ -19,6 +19,8 @@ from .base import TranslationServiceTransport from .grpc import TranslationServiceGrpcTransport from .grpc_asyncio import TranslationServiceGrpcAsyncIOTransport +from .rest import TranslationServiceRestTransport +from .rest import TranslationServiceRestInterceptor # Compile a registry of transports. @@ -27,9 +29,12 @@ ) # type: Dict[str, Type[TranslationServiceTransport]] _transport_registry["grpc"] = TranslationServiceGrpcTransport _transport_registry["grpc_asyncio"] = TranslationServiceGrpcAsyncIOTransport +_transport_registry["rest"] = TranslationServiceRestTransport __all__ = ( "TranslationServiceTransport", "TranslationServiceGrpcTransport", "TranslationServiceGrpcAsyncIOTransport", + "TranslationServiceRestTransport", + "TranslationServiceRestInterceptor", ) diff --git a/google/cloud/translate_v3beta1/services/translation_service/transports/rest.py b/google/cloud/translate_v3beta1/services/translation_service/transports/rest.py new file mode 100644 index 00000000..4b12c39e --- /dev/null +++ b/google/cloud/translate_v3beta1/services/translation_service/transports/rest.py @@ -0,0 +1,1621 @@ +# -*- 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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.translate_v3beta1.types import translation_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import ( + TranslationServiceTransport, + DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO, +) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class TranslationServiceRestInterceptor: + """Interceptor for TranslationService. + + 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 TranslationServiceRestTransport. + + .. code-block:: python + class MyCustomTranslationServiceInterceptor(TranslationServiceRestInterceptor): + def pre_batch_translate_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_translate_document(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_translate_text(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_translate_text(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_glossary(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_glossary(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_glossary(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_glossary(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_detect_language(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_detect_language(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_glossary(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_glossary(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_supported_languages(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_supported_languages(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_glossaries(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_glossaries(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_translate_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_translate_document(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_translate_text(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_translate_text(self, response): + logging.log(f"Received response: {response}") + return response + + transport = TranslationServiceRestTransport(interceptor=MyCustomTranslationServiceInterceptor()) + client = TranslationServiceClient(transport=transport) + + + """ + + def pre_batch_translate_document( + self, + request: translation_service.BatchTranslateDocumentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + translation_service.BatchTranslateDocumentRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for batch_translate_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_batch_translate_document( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for batch_translate_document + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + def pre_batch_translate_text( + self, + request: translation_service.BatchTranslateTextRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + translation_service.BatchTranslateTextRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for batch_translate_text + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_batch_translate_text( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for batch_translate_text + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + def pre_create_glossary( + self, + request: translation_service.CreateGlossaryRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[translation_service.CreateGlossaryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_glossary + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_create_glossary( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_glossary + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + def pre_delete_glossary( + self, + request: translation_service.DeleteGlossaryRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[translation_service.DeleteGlossaryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_glossary + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_delete_glossary( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_glossary + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + def pre_detect_language( + self, + request: translation_service.DetectLanguageRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[translation_service.DetectLanguageRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for detect_language + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_detect_language( + self, response: translation_service.DetectLanguageResponse + ) -> translation_service.DetectLanguageResponse: + """Post-rpc interceptor for detect_language + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + def pre_get_glossary( + self, + request: translation_service.GetGlossaryRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[translation_service.GetGlossaryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_glossary + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_get_glossary( + self, response: translation_service.Glossary + ) -> translation_service.Glossary: + """Post-rpc interceptor for get_glossary + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + def pre_get_supported_languages( + self, + request: translation_service.GetSupportedLanguagesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + translation_service.GetSupportedLanguagesRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for get_supported_languages + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_get_supported_languages( + self, response: translation_service.SupportedLanguages + ) -> translation_service.SupportedLanguages: + """Post-rpc interceptor for get_supported_languages + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + def pre_list_glossaries( + self, + request: translation_service.ListGlossariesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[translation_service.ListGlossariesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_glossaries + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_list_glossaries( + self, response: translation_service.ListGlossariesResponse + ) -> translation_service.ListGlossariesResponse: + """Post-rpc interceptor for list_glossaries + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + def pre_translate_document( + self, + request: translation_service.TranslateDocumentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[translation_service.TranslateDocumentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for translate_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_translate_document( + self, response: translation_service.TranslateDocumentResponse + ) -> translation_service.TranslateDocumentResponse: + """Post-rpc interceptor for translate_document + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + def pre_translate_text( + self, + request: translation_service.TranslateTextRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[translation_service.TranslateTextRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for translate_text + + Override in a subclass to manipulate the request or metadata + before they are sent to the TranslationService server. + """ + return request, metadata + + def post_translate_text( + self, response: translation_service.TranslateTextResponse + ) -> translation_service.TranslateTextResponse: + """Post-rpc interceptor for translate_text + + Override in a subclass to manipulate the response + after it is returned by the TranslationService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class TranslationServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: TranslationServiceRestInterceptor + + +class TranslationServiceRestTransport(TranslationServiceTransport): + """REST backend transport for TranslationService. + + Provides natural language translation operations. + + 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 = "translate.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[TranslationServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or TranslationServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v3beta1/{name=projects/*/locations/*}/operations", + }, + ], + "google.longrunning.Operations.WaitOperation": [ + { + "method": "post", + "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:wait", + "body": "*", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v3beta1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _BatchTranslateDocument(TranslationServiceRestStub): + def __hash__(self): + return hash("BatchTranslateDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.BatchTranslateDocumentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the batch translate document method over HTTP. + + Args: + request (~.translation_service.BatchTranslateDocumentRequest): + The request object. The BatchTranslateDocument request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3beta1/{parent=projects/*/locations/*}:batchTranslateDocument", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_batch_translate_document( + request, metadata + ) + pb_request = translation_service.BatchTranslateDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_translate_document(resp) + return resp + + class _BatchTranslateText(TranslationServiceRestStub): + def __hash__(self): + return hash("BatchTranslateText") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.BatchTranslateTextRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the batch translate text method over HTTP. + + Args: + request (~.translation_service.BatchTranslateTextRequest): + The request object. The batch translation request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3beta1/{parent=projects/*/locations/*}:batchTranslateText", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_batch_translate_text( + request, metadata + ) + pb_request = translation_service.BatchTranslateTextRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_translate_text(resp) + return resp + + class _CreateGlossary(TranslationServiceRestStub): + def __hash__(self): + return hash("CreateGlossary") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.CreateGlossaryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create glossary method over HTTP. + + Args: + request (~.translation_service.CreateGlossaryRequest): + The request object. Request message for CreateGlossary. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3beta1/{parent=projects/*/locations/*}/glossaries", + "body": "glossary", + }, + ] + request, metadata = self._interceptor.pre_create_glossary(request, metadata) + pb_request = translation_service.CreateGlossaryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_glossary(resp) + return resp + + class _DeleteGlossary(TranslationServiceRestStub): + def __hash__(self): + return hash("DeleteGlossary") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.DeleteGlossaryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete glossary method over HTTP. + + Args: + request (~.translation_service.DeleteGlossaryRequest): + The request object. Request message for DeleteGlossary. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v3beta1/{name=projects/*/locations/*/glossaries/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_glossary(request, metadata) + pb_request = translation_service.DeleteGlossaryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_glossary(resp) + return resp + + class _DetectLanguage(TranslationServiceRestStub): + def __hash__(self): + return hash("DetectLanguage") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.DetectLanguageRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.DetectLanguageResponse: + r"""Call the detect language method over HTTP. + + Args: + request (~.translation_service.DetectLanguageRequest): + The request object. The request message for language + detection. + + 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: + ~.translation_service.DetectLanguageResponse: + The response message for language + detection. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3beta1/{parent=projects/*/locations/*}:detectLanguage", + "body": "*", + }, + { + "method": "post", + "uri": "/v3beta1/{parent=projects/*}:detectLanguage", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_detect_language(request, metadata) + pb_request = translation_service.DetectLanguageRequest.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 = translation_service.DetectLanguageResponse() + pb_resp = translation_service.DetectLanguageResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_detect_language(resp) + return resp + + class _GetGlossary(TranslationServiceRestStub): + def __hash__(self): + return hash("GetGlossary") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.GetGlossaryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.Glossary: + r"""Call the get glossary method over HTTP. + + Args: + request (~.translation_service.GetGlossaryRequest): + The request object. Request message for GetGlossary. + 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: + ~.translation_service.Glossary: + Represents a glossary built from user + provided data. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3beta1/{name=projects/*/locations/*/glossaries/*}", + }, + ] + request, metadata = self._interceptor.pre_get_glossary(request, metadata) + pb_request = translation_service.GetGlossaryRequest.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 = translation_service.Glossary() + pb_resp = translation_service.Glossary.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_glossary(resp) + return resp + + class _GetSupportedLanguages(TranslationServiceRestStub): + def __hash__(self): + return hash("GetSupportedLanguages") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.GetSupportedLanguagesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.SupportedLanguages: + r"""Call the get supported languages method over HTTP. + + Args: + request (~.translation_service.GetSupportedLanguagesRequest): + The request object. The request message for discovering + supported languages. + + 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: + ~.translation_service.SupportedLanguages: + The response message for discovering + supported languages. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3beta1/{parent=projects/*/locations/*}/supportedLanguages", + }, + { + "method": "get", + "uri": "/v3beta1/{parent=projects/*}/supportedLanguages", + }, + ] + request, metadata = self._interceptor.pre_get_supported_languages( + request, metadata + ) + pb_request = translation_service.GetSupportedLanguagesRequest.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 = translation_service.SupportedLanguages() + pb_resp = translation_service.SupportedLanguages.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_supported_languages(resp) + return resp + + class _ListGlossaries(TranslationServiceRestStub): + def __hash__(self): + return hash("ListGlossaries") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.ListGlossariesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.ListGlossariesResponse: + r"""Call the list glossaries method over HTTP. + + Args: + request (~.translation_service.ListGlossariesRequest): + The request object. Request message for ListGlossaries. + 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: + ~.translation_service.ListGlossariesResponse: + Response message for ListGlossaries. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3beta1/{parent=projects/*/locations/*}/glossaries", + }, + ] + request, metadata = self._interceptor.pre_list_glossaries(request, metadata) + pb_request = translation_service.ListGlossariesRequest.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 = translation_service.ListGlossariesResponse() + pb_resp = translation_service.ListGlossariesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_glossaries(resp) + return resp + + class _TranslateDocument(TranslationServiceRestStub): + def __hash__(self): + return hash("TranslateDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.TranslateDocumentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.TranslateDocumentResponse: + r"""Call the translate document method over HTTP. + + Args: + request (~.translation_service.TranslateDocumentRequest): + The request object. A document translation request. + 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: + ~.translation_service.TranslateDocumentResponse: + A translated document response + message. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3beta1/{parent=projects/*/locations/*}:translateDocument", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_translate_document( + request, metadata + ) + pb_request = translation_service.TranslateDocumentRequest.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 = translation_service.TranslateDocumentResponse() + pb_resp = translation_service.TranslateDocumentResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_translate_document(resp) + return resp + + class _TranslateText(TranslationServiceRestStub): + def __hash__(self): + return hash("TranslateText") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: translation_service.TranslateTextRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.TranslateTextResponse: + r"""Call the translate text method over HTTP. + + Args: + request (~.translation_service.TranslateTextRequest): + The request object. The request message for synchronous + translation. + + 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: + ~.translation_service.TranslateTextResponse: + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3beta1/{parent=projects/*/locations/*}:translateText", + "body": "*", + }, + { + "method": "post", + "uri": "/v3beta1/{parent=projects/*}:translateText", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_translate_text(request, metadata) + pb_request = translation_service.TranslateTextRequest.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 = translation_service.TranslateTextResponse() + pb_resp = translation_service.TranslateTextResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_translate_text(resp) + return resp + + @property + def batch_translate_document( + self, + ) -> Callable[ + [translation_service.BatchTranslateDocumentRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchTranslateDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_translate_text( + self, + ) -> Callable[ + [translation_service.BatchTranslateTextRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchTranslateText(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_glossary( + self, + ) -> Callable[ + [translation_service.CreateGlossaryRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateGlossary(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_glossary( + self, + ) -> Callable[ + [translation_service.DeleteGlossaryRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteGlossary(self._session, self._host, self._interceptor) # type: ignore + + @property + def detect_language( + self, + ) -> Callable[ + [translation_service.DetectLanguageRequest], + translation_service.DetectLanguageResponse, + ]: + # 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._DetectLanguage(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_glossary( + self, + ) -> Callable[ + [translation_service.GetGlossaryRequest], translation_service.Glossary + ]: + # 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._GetGlossary(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_supported_languages( + self, + ) -> Callable[ + [translation_service.GetSupportedLanguagesRequest], + translation_service.SupportedLanguages, + ]: + # 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._GetSupportedLanguages(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_glossaries( + self, + ) -> Callable[ + [translation_service.ListGlossariesRequest], + translation_service.ListGlossariesResponse, + ]: + # 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._ListGlossaries(self._session, self._host, self._interceptor) # type: ignore + + @property + def translate_document( + self, + ) -> Callable[ + [translation_service.TranslateDocumentRequest], + translation_service.TranslateDocumentResponse, + ]: + # 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._TranslateDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def translate_text( + self, + ) -> Callable[ + [translation_service.TranslateTextRequest], + translation_service.TranslateTextResponse, + ]: + # 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._TranslateText(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("TranslationServiceRestTransport",) diff --git a/google/cloud/translate_v3beta1/types/translation_service.py b/google/cloud/translate_v3beta1/types/translation_service.py index ca2e36f1..f0dc9eb8 100644 --- a/google/cloud/translate_v3beta1/types/translation_service.py +++ b/google/cloud/translate_v3beta1/types/translation_service.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence import proto # type: ignore diff --git a/scripts/fixup_translate_v3_keywords.py b/scripts/fixup_translate_v3_keywords.py index 8045640a..c621c306 100644 --- a/scripts/fixup_translate_v3_keywords.py +++ b/scripts/fixup_translate_v3_keywords.py @@ -39,7 +39,7 @@ def partition( class translateCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_translate_document': ('parent', 'source_language_code', 'target_language_codes', 'input_configs', 'output_config', 'models', 'glossaries', 'format_conversions', ), + 'batch_translate_document': ('parent', 'source_language_code', 'target_language_codes', 'input_configs', 'output_config', 'models', 'glossaries', 'format_conversions', 'customized_attribution', ), 'batch_translate_text': ('parent', 'source_language_code', 'target_language_codes', 'input_configs', 'output_config', 'models', 'glossaries', 'labels', ), 'create_glossary': ('parent', 'glossary', ), 'delete_glossary': ('name', ), @@ -47,7 +47,7 @@ class translateCallTransformer(cst.CSTTransformer): 'get_glossary': ('name', ), 'get_supported_languages': ('parent', 'display_language_code', 'model', ), 'list_glossaries': ('parent', 'page_size', 'page_token', 'filter', ), - 'translate_document': ('parent', 'target_language_code', 'document_input_config', 'source_language_code', 'document_output_config', 'model', 'glossary_config', 'labels', ), + 'translate_document': ('parent', 'target_language_code', 'document_input_config', 'source_language_code', 'document_output_config', 'model', 'glossary_config', 'labels', 'customized_attribution', 'is_translate_native_pdf_only', 'enable_shadow_removal_native_pdf', ), 'translate_text': ('contents', 'target_language_code', 'parent', 'mime_type', 'source_language_code', 'model', 'glossary_config', 'labels', ), } diff --git a/tests/unit/gapic/translate_v3/test_translation_service.py b/tests/unit/gapic/translate_v3/test_translation_service.py index 4ee5aba2..899fbc96 100644 --- a/tests/unit/gapic/translate_v3/test_translation_service.py +++ b/tests/unit/gapic/translate_v3/test_translation_service.py @@ -24,10 +24,17 @@ import grpc from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format from google.api_core import client_options from google.api_core import exceptions as core_exceptions @@ -106,6 +113,7 @@ def test__get_default_mtls_endpoint(): [ (TranslationServiceClient, "grpc"), (TranslationServiceAsyncClient, "grpc_asyncio"), + (TranslationServiceClient, "rest"), ], ) def test_translation_service_client_from_service_account_info( @@ -121,7 +129,11 @@ def test_translation_service_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("translate.googleapis.com:443") + assert client.transport._host == ( + "translate.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://translate.googleapis.com" + ) @pytest.mark.parametrize( @@ -129,6 +141,7 @@ def test_translation_service_client_from_service_account_info( [ (transports.TranslationServiceGrpcTransport, "grpc"), (transports.TranslationServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.TranslationServiceRestTransport, "rest"), ], ) def test_translation_service_client_service_account_always_use_jwt( @@ -154,6 +167,7 @@ def test_translation_service_client_service_account_always_use_jwt( [ (TranslationServiceClient, "grpc"), (TranslationServiceAsyncClient, "grpc_asyncio"), + (TranslationServiceClient, "rest"), ], ) def test_translation_service_client_from_service_account_file( @@ -176,13 +190,18 @@ def test_translation_service_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("translate.googleapis.com:443") + assert client.transport._host == ( + "translate.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://translate.googleapis.com" + ) def test_translation_service_client_get_transport_class(): transport = TranslationServiceClient.get_transport_class() available_transports = [ transports.TranslationServiceGrpcTransport, + transports.TranslationServiceRestTransport, ] assert transport in available_transports @@ -199,6 +218,7 @@ def test_translation_service_client_get_transport_class(): transports.TranslationServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (TranslationServiceClient, transports.TranslationServiceRestTransport, "rest"), ], ) @mock.patch.object( @@ -354,6 +374,18 @@ def test_translation_service_client_client_options( "grpc_asyncio", "false", ), + ( + TranslationServiceClient, + transports.TranslationServiceRestTransport, + "rest", + "true", + ), + ( + TranslationServiceClient, + transports.TranslationServiceRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -553,6 +585,7 @@ def test_translation_service_client_get_mtls_endpoint_and_cert_source(client_cla transports.TranslationServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (TranslationServiceClient, transports.TranslationServiceRestTransport, "rest"), ], ) def test_translation_service_client_client_options_scopes( @@ -593,6 +626,12 @@ def test_translation_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + TranslationServiceClient, + transports.TranslationServiceRestTransport, + "rest", + None, + ), ], ) def test_translation_service_client_client_options_credentials_file( @@ -2833,6 +2872,7 @@ def test_get_glossary(request_type, transport: str = "grpc"): call.return_value = translation_service.Glossary( name="name_value", entry_count=1210, + display_name="display_name_value", language_pair=translation_service.Glossary.LanguageCodePair( source_language_code="source_language_code_value" ), @@ -2848,6 +2888,7 @@ def test_get_glossary(request_type, transport: str = "grpc"): assert isinstance(response, translation_service.Glossary) assert response.name == "name_value" assert response.entry_count == 1210 + assert response.display_name == "display_name_value" def test_get_glossary_empty_call(): @@ -2886,6 +2927,7 @@ async def test_get_glossary_async( translation_service.Glossary( name="name_value", entry_count=1210, + display_name="display_name_value", ) ) response = await client.get_glossary(request) @@ -2899,6 +2941,7 @@ async def test_get_glossary_async( assert isinstance(response, translation_service.Glossary) assert response.name == "name_value" assert response.entry_count == 1210 + assert response.display_name == "display_name_value" @pytest.mark.asyncio @@ -3276,173 +3319,2982 @@ async def test_delete_glossary_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.TranslationServiceGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + translation_service.TranslateTextRequest, + dict, + ], +) +def test_translate_text_rest(request_type): + client = TranslationServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = TranslationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = translation_service.TranslateTextResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = translation_service.TranslateTextResponse.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.translate_text(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.TranslateTextResponse) + + +def test_translate_text_rest_required_fields( + request_type=translation_service.TranslateTextRequest, +): + transport_class = transports.TranslationServiceRestTransport + + request_init = {} + request_init["contents"] = "" + request_init["target_language_code"] = "" + 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 a credentials file and a transport instance. - transport = transports.TranslationServiceGrpcTransport( + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).translate_text._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["contents"] = "contents_value" + jsonified_request["targetLanguageCode"] = "target_language_code_value" + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).translate_text._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "contents" in jsonified_request + assert jsonified_request["contents"] == "contents_value" + assert "targetLanguageCode" in jsonified_request + assert jsonified_request["targetLanguageCode"] == "target_language_code_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = TranslationServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = TranslationServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = translation_service.TranslateTextResponse() + # 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 = translation_service.TranslateTextResponse.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.translate_text(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_translate_text_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.translate_text._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "contents", + "targetLanguageCode", + "parent", + ) ) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.TranslationServiceGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_translate_text_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TranslationServiceClient( - client_options=options, - transport=transport, + client = TranslationServiceClient(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.TranslationServiceRestInterceptor, "post_translate_text" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_translate_text" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.TranslateTextRequest.pb( + translation_service.TranslateTextRequest() ) - - # 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 = TranslationServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + 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 = translation_service.TranslateTextResponse.to_json( + translation_service.TranslateTextResponse() ) - # It is an error to provide scopes and a transport instance. - transport = transports.TranslationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TranslationServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + request = translation_service.TranslateTextRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = translation_service.TranslateTextResponse() + + client.translate_text( + 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.TranslationServiceGrpcTransport( + +def test_translate_text_rest_bad_request( + transport: str = "rest", request_type=translation_service.TranslateTextRequest +): + client = TranslationServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = TranslationServiceClient(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.TranslationServiceGrpcTransport( + # 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.translate_text(request) + + +def test_translate_text_rest_flattened(): + client = TranslationServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.TranslationServiceGrpcAsyncIOTransport( + # 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 = translation_service.TranslateTextResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + target_language_code="target_language_code_value", + contents=["contents_value"], + model="model_value", + mime_type="mime_type_value", + source_language_code="source_language_code_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 = translation_service.TranslateTextResponse.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.translate_text(**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/v3/{parent=projects/*/locations/*}:translateText" + % client.transport._host, + args[1], + ) + + +def test_translate_text_rest_flattened_error(transport: str = "rest"): + client = TranslationServiceClient( 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.translate_text( + translation_service.TranslateTextRequest(), + parent="parent_value", + target_language_code="target_language_code_value", + contents=["contents_value"], + model="model_value", + mime_type="mime_type_value", + source_language_code="source_language_code_value", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.TranslationServiceGrpcTransport, - transports.TranslationServiceGrpcAsyncIOTransport, - ], -) -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_translate_text_rest_error(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + translation_service.DetectLanguageRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = TranslationServiceClient.get_transport_class(transport_name)( +def test_detect_language_rest(request_type): + client = TranslationServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = translation_service.DetectLanguageResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = translation_service.DetectLanguageResponse.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.detect_language(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.DetectLanguageResponse) + + +def test_detect_language_rest_required_fields( + request_type=translation_service.DetectLanguageRequest, +): + transport_class = transports.TranslationServiceRestTransport + + 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() + ).detect_language._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() + ).detect_language._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" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = TranslationServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.TranslationServiceGrpcTransport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = translation_service.DetectLanguageResponse() + # 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 = translation_service.DetectLanguageResponse.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.detect_language(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_detect_language_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) + unset_fields = transport.detect_language._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) -def test_translation_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.TranslationServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_detect_language_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), + ) + client = TranslationServiceClient(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.TranslationServiceRestInterceptor, "post_detect_language" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_detect_language" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.DetectLanguageRequest.pb( + translation_service.DetectLanguageRequest() + ) + 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 = translation_service.DetectLanguageResponse.to_json( + translation_service.DetectLanguageResponse() ) + request = translation_service.DetectLanguageRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = translation_service.DetectLanguageResponse() -def test_translation_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.translate_v3.services.translation_service.transports.TranslationServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.TranslationServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), + client.detect_language( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "translate_text", - "detect_language", - "get_supported_languages", - "translate_document", - "batch_translate_text", - "batch_translate_document", - "create_glossary", - "list_glossaries", - "get_glossary", - "delete_glossary", - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + pre.assert_called_once() + post.assert_called_once() - with pytest.raises(NotImplementedError): - transport.close() - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client +def test_detect_language_rest_bad_request( + transport: str = "rest", request_type=translation_service.DetectLanguageRequest +): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.detect_language(request) + + +def test_detect_language_rest_flattened(): + client = TranslationServiceClient( + 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 = translation_service.DetectLanguageResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + model="model_value", + mime_type="mime_type_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 = translation_service.DetectLanguageResponse.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.detect_language(**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/v3/{parent=projects/*/locations/*}:detectLanguage" + % client.transport._host, + args[1], + ) + + +def test_detect_language_rest_flattened_error(transport: str = "rest"): + client = TranslationServiceClient( + 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.detect_language( + translation_service.DetectLanguageRequest(), + parent="parent_value", + model="model_value", + mime_type="mime_type_value", + content="content_value", + ) + + +def test_detect_language_rest_error(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + translation_service.GetSupportedLanguagesRequest, + dict, + ], +) +def test_get_supported_languages_rest(request_type): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = translation_service.SupportedLanguages() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = translation_service.SupportedLanguages.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_supported_languages(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.SupportedLanguages) + + +def test_get_supported_languages_rest_required_fields( + request_type=translation_service.GetSupportedLanguagesRequest, +): + transport_class = transports.TranslationServiceRestTransport + + 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() + ).get_supported_languages._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() + ).get_supported_languages._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "display_language_code", + "model", + ) + ) + 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 = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = translation_service.SupportedLanguages() + # 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 = translation_service.SupportedLanguages.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_supported_languages(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_supported_languages_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_supported_languages._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "displayLanguageCode", + "model", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_supported_languages_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), + ) + client = TranslationServiceClient(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.TranslationServiceRestInterceptor, "post_get_supported_languages" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_get_supported_languages" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.GetSupportedLanguagesRequest.pb( + translation_service.GetSupportedLanguagesRequest() + ) + 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 = translation_service.SupportedLanguages.to_json( + translation_service.SupportedLanguages() + ) + + request = translation_service.GetSupportedLanguagesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = translation_service.SupportedLanguages() + + client.get_supported_languages( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_supported_languages_rest_bad_request( + transport: str = "rest", + request_type=translation_service.GetSupportedLanguagesRequest, +): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_supported_languages(request) + + +def test_get_supported_languages_rest_flattened(): + client = TranslationServiceClient( + 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 = translation_service.SupportedLanguages() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + model="model_value", + display_language_code="display_language_code_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 = translation_service.SupportedLanguages.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_supported_languages(**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/v3/{parent=projects/*/locations/*}/supportedLanguages" + % client.transport._host, + args[1], + ) + + +def test_get_supported_languages_rest_flattened_error(transport: str = "rest"): + client = TranslationServiceClient( + 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_supported_languages( + translation_service.GetSupportedLanguagesRequest(), + parent="parent_value", + model="model_value", + display_language_code="display_language_code_value", + ) + + +def test_get_supported_languages_rest_error(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + translation_service.TranslateDocumentRequest, + dict, + ], +) +def test_translate_document_rest(request_type): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = translation_service.TranslateDocumentResponse( + model="model_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = translation_service.TranslateDocumentResponse.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.translate_document(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.TranslateDocumentResponse) + assert response.model == "model_value" + + +def test_translate_document_rest_required_fields( + request_type=translation_service.TranslateDocumentRequest, +): + transport_class = transports.TranslationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["target_language_code"] = "" + 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() + ).translate_document._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" + jsonified_request["targetLanguageCode"] = "target_language_code_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).translate_document._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" + assert "targetLanguageCode" in jsonified_request + assert jsonified_request["targetLanguageCode"] == "target_language_code_value" + + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = translation_service.TranslateDocumentResponse() + # 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 = translation_service.TranslateDocumentResponse.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.translate_document(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_translate_document_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.translate_document._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "targetLanguageCode", + "documentInputConfig", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_translate_document_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), + ) + client = TranslationServiceClient(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.TranslationServiceRestInterceptor, "post_translate_document" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_translate_document" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.TranslateDocumentRequest.pb( + translation_service.TranslateDocumentRequest() + ) + 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 = ( + translation_service.TranslateDocumentResponse.to_json( + translation_service.TranslateDocumentResponse() + ) + ) + + request = translation_service.TranslateDocumentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = translation_service.TranslateDocumentResponse() + + client.translate_document( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_translate_document_rest_bad_request( + transport: str = "rest", request_type=translation_service.TranslateDocumentRequest +): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.translate_document(request) + + +def test_translate_document_rest_error(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + translation_service.BatchTranslateTextRequest, + dict, + ], +) +def test_batch_translate_text_rest(request_type): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.batch_translate_text(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_batch_translate_text_rest_required_fields( + request_type=translation_service.BatchTranslateTextRequest, +): + transport_class = transports.TranslationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["source_language_code"] = "" + request_init["target_language_codes"] = "" + 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() + ).batch_translate_text._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" + jsonified_request["sourceLanguageCode"] = "source_language_code_value" + jsonified_request["targetLanguageCodes"] = "target_language_codes_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_translate_text._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" + assert "sourceLanguageCode" in jsonified_request + assert jsonified_request["sourceLanguageCode"] == "source_language_code_value" + assert "targetLanguageCodes" in jsonified_request + assert jsonified_request["targetLanguageCodes"] == "target_language_codes_value" + + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.batch_translate_text(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_batch_translate_text_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_translate_text._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "sourceLanguageCode", + "targetLanguageCodes", + "inputConfigs", + "outputConfig", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_translate_text_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), + ) + client = TranslationServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TranslationServiceRestInterceptor, "post_batch_translate_text" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_batch_translate_text" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.BatchTranslateTextRequest.pb( + translation_service.BatchTranslateTextRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = translation_service.BatchTranslateTextRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.batch_translate_text( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_translate_text_rest_bad_request( + transport: str = "rest", request_type=translation_service.BatchTranslateTextRequest +): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_translate_text(request) + + +def test_batch_translate_text_rest_error(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + translation_service.BatchTranslateDocumentRequest, + dict, + ], +) +def test_batch_translate_document_rest(request_type): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.batch_translate_document(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_batch_translate_document_rest_required_fields( + request_type=translation_service.BatchTranslateDocumentRequest, +): + transport_class = transports.TranslationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["source_language_code"] = "" + request_init["target_language_codes"] = "" + 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() + ).batch_translate_document._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" + jsonified_request["sourceLanguageCode"] = "source_language_code_value" + jsonified_request["targetLanguageCodes"] = "target_language_codes_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_translate_document._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" + assert "sourceLanguageCode" in jsonified_request + assert jsonified_request["sourceLanguageCode"] == "source_language_code_value" + assert "targetLanguageCodes" in jsonified_request + assert jsonified_request["targetLanguageCodes"] == "target_language_codes_value" + + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.batch_translate_document(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_batch_translate_document_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_translate_document._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "sourceLanguageCode", + "targetLanguageCodes", + "inputConfigs", + "outputConfig", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_translate_document_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), + ) + client = TranslationServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TranslationServiceRestInterceptor, "post_batch_translate_document" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_batch_translate_document" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.BatchTranslateDocumentRequest.pb( + translation_service.BatchTranslateDocumentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = translation_service.BatchTranslateDocumentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.batch_translate_document( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_translate_document_rest_bad_request( + transport: str = "rest", + request_type=translation_service.BatchTranslateDocumentRequest, +): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_translate_document(request) + + +def test_batch_translate_document_rest_flattened(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + source_language_code="source_language_code_value", + target_language_codes=["target_language_codes_value"], + input_configs=[ + translation_service.BatchDocumentInputConfig( + gcs_source=translation_service.GcsSource( + input_uri="input_uri_value" + ) + ) + ], + output_config=translation_service.BatchDocumentOutputConfig( + gcs_destination=translation_service.GcsDestination( + output_uri_prefix="output_uri_prefix_value" + ) + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.batch_translate_document(**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/v3/{parent=projects/*/locations/*}:batchTranslateDocument" + % client.transport._host, + args[1], + ) + + +def test_batch_translate_document_rest_flattened_error(transport: str = "rest"): + client = TranslationServiceClient( + 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.batch_translate_document( + translation_service.BatchTranslateDocumentRequest(), + parent="parent_value", + source_language_code="source_language_code_value", + target_language_codes=["target_language_codes_value"], + input_configs=[ + translation_service.BatchDocumentInputConfig( + gcs_source=translation_service.GcsSource( + input_uri="input_uri_value" + ) + ) + ], + output_config=translation_service.BatchDocumentOutputConfig( + gcs_destination=translation_service.GcsDestination( + output_uri_prefix="output_uri_prefix_value" + ) + ), + ) + + +def test_batch_translate_document_rest_error(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + translation_service.CreateGlossaryRequest, + dict, + ], +) +def test_create_glossary_rest(request_type): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["glossary"] = { + "name": "name_value", + "language_pair": { + "source_language_code": "source_language_code_value", + "target_language_code": "target_language_code_value", + }, + "language_codes_set": { + "language_codes": ["language_codes_value1", "language_codes_value2"] + }, + "input_config": {"gcs_source": {"input_uri": "input_uri_value"}}, + "entry_count": 1210, + "submit_time": {"seconds": 751, "nanos": 543}, + "end_time": {}, + "display_name": "display_name_value", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_glossary(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_glossary_rest_required_fields( + request_type=translation_service.CreateGlossaryRequest, +): + transport_class = transports.TranslationServiceRestTransport + + 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() + ).create_glossary._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_glossary._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 = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_glossary(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_glossary_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_glossary._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "glossary", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_glossary_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), + ) + client = TranslationServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TranslationServiceRestInterceptor, "post_create_glossary" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_create_glossary" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.CreateGlossaryRequest.pb( + translation_service.CreateGlossaryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = translation_service.CreateGlossaryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_glossary( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_glossary_rest_bad_request( + transport: str = "rest", request_type=translation_service.CreateGlossaryRequest +): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["glossary"] = { + "name": "name_value", + "language_pair": { + "source_language_code": "source_language_code_value", + "target_language_code": "target_language_code_value", + }, + "language_codes_set": { + "language_codes": ["language_codes_value1", "language_codes_value2"] + }, + "input_config": {"gcs_source": {"input_uri": "input_uri_value"}}, + "entry_count": 1210, + "submit_time": {"seconds": 751, "nanos": 543}, + "end_time": {}, + "display_name": "display_name_value", + } + 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.create_glossary(request) + + +def test_create_glossary_rest_flattened(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + glossary=translation_service.Glossary(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_glossary(**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/v3/{parent=projects/*/locations/*}/glossaries" % client.transport._host, + args[1], + ) + + +def test_create_glossary_rest_flattened_error(transport: str = "rest"): + client = TranslationServiceClient( + 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.create_glossary( + translation_service.CreateGlossaryRequest(), + parent="parent_value", + glossary=translation_service.Glossary(name="name_value"), + ) + + +def test_create_glossary_rest_error(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + translation_service.ListGlossariesRequest, + dict, + ], +) +def test_list_glossaries_rest(request_type): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = translation_service.ListGlossariesResponse( + 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 = translation_service.ListGlossariesResponse.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_glossaries(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGlossariesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_glossaries_rest_required_fields( + request_type=translation_service.ListGlossariesRequest, +): + transport_class = transports.TranslationServiceRestTransport + + 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_glossaries._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_glossaries._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = translation_service.ListGlossariesResponse() + # 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 = translation_service.ListGlossariesResponse.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_glossaries(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_glossaries_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_glossaries._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_glossaries_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), + ) + client = TranslationServiceClient(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.TranslationServiceRestInterceptor, "post_list_glossaries" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_list_glossaries" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.ListGlossariesRequest.pb( + translation_service.ListGlossariesRequest() + ) + 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 = translation_service.ListGlossariesResponse.to_json( + translation_service.ListGlossariesResponse() + ) + + request = translation_service.ListGlossariesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = translation_service.ListGlossariesResponse() + + client.list_glossaries( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_glossaries_rest_bad_request( + transport: str = "rest", request_type=translation_service.ListGlossariesRequest +): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_glossaries(request) + + +def test_list_glossaries_rest_flattened(): + client = TranslationServiceClient( + 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 = translation_service.ListGlossariesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = translation_service.ListGlossariesResponse.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_glossaries(**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/v3/{parent=projects/*/locations/*}/glossaries" % client.transport._host, + args[1], + ) + + +def test_list_glossaries_rest_flattened_error(transport: str = "rest"): + client = TranslationServiceClient( + 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_glossaries( + translation_service.ListGlossariesRequest(), + parent="parent_value", + ) + + +def test_list_glossaries_rest_pager(transport: str = "rest"): + client = TranslationServiceClient( + 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 = ( + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + translation_service.Glossary(), + ], + next_page_token="abc", + ), + translation_service.ListGlossariesResponse( + glossaries=[], + next_page_token="def", + ), + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + ], + next_page_token="ghi", + ), + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + translation_service.ListGlossariesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_glossaries(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, translation_service.Glossary) for i in results) + + pages = list(client.list_glossaries(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", + [ + translation_service.GetGlossaryRequest, + dict, + ], +) +def test_get_glossary_rest(request_type): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/glossaries/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = translation_service.Glossary( + name="name_value", + entry_count=1210, + display_name="display_name_value", + language_pair=translation_service.Glossary.LanguageCodePair( + source_language_code="source_language_code_value" + ), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = translation_service.Glossary.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_glossary(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.Glossary) + assert response.name == "name_value" + assert response.entry_count == 1210 + assert response.display_name == "display_name_value" + + +def test_get_glossary_rest_required_fields( + request_type=translation_service.GetGlossaryRequest, +): + transport_class = transports.TranslationServiceRestTransport + + 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_glossary._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_glossary._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 = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = translation_service.Glossary() + # 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 = translation_service.Glossary.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_glossary(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_glossary_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_glossary._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_glossary_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), + ) + client = TranslationServiceClient(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.TranslationServiceRestInterceptor, "post_get_glossary" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_get_glossary" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.GetGlossaryRequest.pb( + translation_service.GetGlossaryRequest() + ) + 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 = translation_service.Glossary.to_json( + translation_service.Glossary() + ) + + request = translation_service.GetGlossaryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = translation_service.Glossary() + + client.get_glossary( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_glossary_rest_bad_request( + transport: str = "rest", request_type=translation_service.GetGlossaryRequest +): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/glossaries/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_glossary(request) + + +def test_get_glossary_rest_flattened(): + client = TranslationServiceClient( + 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 = translation_service.Glossary() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/glossaries/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = translation_service.Glossary.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_glossary(**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/v3/{name=projects/*/locations/*/glossaries/*}" % client.transport._host, + args[1], + ) + + +def test_get_glossary_rest_flattened_error(transport: str = "rest"): + client = TranslationServiceClient( + 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_glossary( + translation_service.GetGlossaryRequest(), + name="name_value", + ) + + +def test_get_glossary_rest_error(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + translation_service.DeleteGlossaryRequest, + dict, + ], +) +def test_delete_glossary_rest(request_type): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/glossaries/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_glossary(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_glossary_rest_required_fields( + request_type=translation_service.DeleteGlossaryRequest, +): + transport_class = transports.TranslationServiceRestTransport + + 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_glossary._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_glossary._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 = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_glossary(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_glossary_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_glossary._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_glossary_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), + ) + client = TranslationServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TranslationServiceRestInterceptor, "post_delete_glossary" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_delete_glossary" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.DeleteGlossaryRequest.pb( + translation_service.DeleteGlossaryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = translation_service.DeleteGlossaryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_glossary( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_glossary_rest_bad_request( + transport: str = "rest", request_type=translation_service.DeleteGlossaryRequest +): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/glossaries/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_glossary(request) + + +def test_delete_glossary_rest_flattened(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/glossaries/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_glossary(**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/v3/{name=projects/*/locations/*/glossaries/*}" % client.transport._host, + args[1], + ) + + +def test_delete_glossary_rest_flattened_error(transport: str = "rest"): + client = TranslationServiceClient( + 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_glossary( + translation_service.DeleteGlossaryRequest(), + name="name_value", + ) + + +def test_delete_glossary_rest_error(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TranslationServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TranslationServiceClient( + 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 = TranslationServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TranslationServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TranslationServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TranslationServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TranslationServiceGrpcTransport, + transports.TranslationServiceGrpcAsyncIOTransport, + transports.TranslationServiceRestTransport, + ], +) +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 = TranslationServiceClient.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 = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.TranslationServiceGrpcTransport, + ) + + +def test_translation_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.TranslationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_translation_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.translate_v3.services.translation_service.transports.TranslationServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.TranslationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "translate_text", + "detect_language", + "get_supported_languages", + "translate_document", + "batch_translate_text", + "batch_translate_document", + "create_glossary", + "list_glossaries", + "get_glossary", + "delete_glossary", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() def test_translation_service_base_transport_with_credentials_file(): @@ -3523,6 +6375,7 @@ def test_translation_service_transport_auth_adc(transport_class): [ transports.TranslationServiceGrpcTransport, transports.TranslationServiceGrpcAsyncIOTransport, + transports.TranslationServiceRestTransport, ], ) def test_translation_service_transport_auth_gdch_credentials(transport_class): @@ -3625,11 +6478,40 @@ def test_translation_service_grpc_transport_client_cert_source_for_mtls( ) +def test_translation_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.TranslationServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_translation_service_rest_lro_client(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_translation_service_host_no_port(transport_name): @@ -3640,7 +6522,11 @@ def test_translation_service_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("translate.googleapis.com:443") + assert client.transport._host == ( + "translate.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://translate.googleapis.com" + ) @pytest.mark.parametrize( @@ -3648,6 +6534,7 @@ def test_translation_service_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_translation_service_host_with_port(transport_name): @@ -3658,7 +6545,60 @@ def test_translation_service_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("translate.googleapis.com:8000") + assert client.transport._host == ( + "translate.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://translate.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_translation_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = TranslationServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = TranslationServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.translate_text._session + session2 = client2.transport.translate_text._session + assert session1 != session2 + session1 = client1.transport.detect_language._session + session2 = client2.transport.detect_language._session + assert session1 != session2 + session1 = client1.transport.get_supported_languages._session + session2 = client2.transport.get_supported_languages._session + assert session1 != session2 + session1 = client1.transport.translate_document._session + session2 = client2.transport.translate_document._session + assert session1 != session2 + session1 = client1.transport.batch_translate_text._session + session2 = client2.transport.batch_translate_text._session + assert session1 != session2 + session1 = client1.transport.batch_translate_document._session + session2 = client2.transport.batch_translate_document._session + assert session1 != session2 + session1 = client1.transport.create_glossary._session + session2 = client2.transport.create_glossary._session + assert session1 != session2 + session1 = client1.transport.list_glossaries._session + session2 = client2.transport.list_glossaries._session + assert session1 != session2 + session1 = client1.transport.get_glossary._session + session2 = client2.transport.get_glossary._session + assert session1 != session2 + session1 = client1.transport.delete_glossary._session + session2 = client2.transport.delete_glossary._session + assert session1 != session2 def test_translation_service_grpc_transport_channel(): @@ -3989,6 +6929,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -4006,6 +6947,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/translate_v3beta1/test_translation_service.py b/tests/unit/gapic/translate_v3beta1/test_translation_service.py index 6770b124..d226dd57 100644 --- a/tests/unit/gapic/translate_v3beta1/test_translation_service.py +++ b/tests/unit/gapic/translate_v3beta1/test_translation_service.py @@ -24,10 +24,17 @@ import grpc from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format from google.api_core import client_options from google.api_core import exceptions as core_exceptions @@ -106,6 +113,7 @@ def test__get_default_mtls_endpoint(): [ (TranslationServiceClient, "grpc"), (TranslationServiceAsyncClient, "grpc_asyncio"), + (TranslationServiceClient, "rest"), ], ) def test_translation_service_client_from_service_account_info( @@ -121,7 +129,11 @@ def test_translation_service_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("translate.googleapis.com:443") + assert client.transport._host == ( + "translate.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://translate.googleapis.com" + ) @pytest.mark.parametrize( @@ -129,6 +141,7 @@ def test_translation_service_client_from_service_account_info( [ (transports.TranslationServiceGrpcTransport, "grpc"), (transports.TranslationServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.TranslationServiceRestTransport, "rest"), ], ) def test_translation_service_client_service_account_always_use_jwt( @@ -154,6 +167,7 @@ def test_translation_service_client_service_account_always_use_jwt( [ (TranslationServiceClient, "grpc"), (TranslationServiceAsyncClient, "grpc_asyncio"), + (TranslationServiceClient, "rest"), ], ) def test_translation_service_client_from_service_account_file( @@ -176,13 +190,18 @@ def test_translation_service_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("translate.googleapis.com:443") + assert client.transport._host == ( + "translate.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://translate.googleapis.com" + ) def test_translation_service_client_get_transport_class(): transport = TranslationServiceClient.get_transport_class() available_transports = [ transports.TranslationServiceGrpcTransport, + transports.TranslationServiceRestTransport, ] assert transport in available_transports @@ -199,6 +218,7 @@ def test_translation_service_client_get_transport_class(): transports.TranslationServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (TranslationServiceClient, transports.TranslationServiceRestTransport, "rest"), ], ) @mock.patch.object( @@ -354,6 +374,18 @@ def test_translation_service_client_client_options( "grpc_asyncio", "false", ), + ( + TranslationServiceClient, + transports.TranslationServiceRestTransport, + "rest", + "true", + ), + ( + TranslationServiceClient, + transports.TranslationServiceRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -553,6 +585,7 @@ def test_translation_service_client_get_mtls_endpoint_and_cert_source(client_cla transports.TranslationServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (TranslationServiceClient, transports.TranslationServiceRestTransport, "rest"), ], ) def test_translation_service_client_client_options_scopes( @@ -593,6 +626,12 @@ def test_translation_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + TranslationServiceClient, + transports.TranslationServiceRestTransport, + "rest", + None, + ), ], ) def test_translation_service_client_client_options_credentials_file( @@ -3148,226 +3187,2970 @@ async def test_delete_glossary_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.TranslationServiceGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + translation_service.TranslateTextRequest, + dict, + ], +) +def test_translate_text_rest(request_type): + client = TranslationServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = TranslationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = translation_service.TranslateTextResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = translation_service.TranslateTextResponse.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.translate_text(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.TranslateTextResponse) + + +def test_translate_text_rest_required_fields( + request_type=translation_service.TranslateTextRequest, +): + transport_class = transports.TranslationServiceRestTransport + + request_init = {} + request_init["contents"] = "" + request_init["target_language_code"] = "" + 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 a credentials file and a transport instance. - transport = transports.TranslationServiceGrpcTransport( + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).translate_text._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["contents"] = "contents_value" + jsonified_request["targetLanguageCode"] = "target_language_code_value" + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).translate_text._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "contents" in jsonified_request + assert jsonified_request["contents"] == "contents_value" + assert "targetLanguageCode" in jsonified_request + assert jsonified_request["targetLanguageCode"] == "target_language_code_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = TranslationServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = TranslationServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = translation_service.TranslateTextResponse() + # 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 = translation_service.TranslateTextResponse.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.translate_text(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_translate_text_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.translate_text._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "contents", + "targetLanguageCode", + "parent", + ) ) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.TranslationServiceGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_translate_text_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TranslationServiceClient( - client_options=options, - transport=transport, + client = TranslationServiceClient(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.TranslationServiceRestInterceptor, "post_translate_text" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_translate_text" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.TranslateTextRequest.pb( + translation_service.TranslateTextRequest() ) - - # 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 = TranslationServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + 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 = translation_service.TranslateTextResponse.to_json( + translation_service.TranslateTextResponse() ) - # It is an error to provide scopes and a transport instance. - transport = transports.TranslationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TranslationServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + request = translation_service.TranslateTextRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = translation_service.TranslateTextResponse() + + client.translate_text( + 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.TranslationServiceGrpcTransport( + +def test_translate_text_rest_bad_request( + transport: str = "rest", request_type=translation_service.TranslateTextRequest +): + client = TranslationServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = TranslationServiceClient(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.TranslationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # 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.translate_text(request) - transport = transports.TranslationServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), + +def test_translate_text_rest_error(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - channel = transport.grpc_channel - assert channel @pytest.mark.parametrize( - "transport_class", + "request_type", [ - transports.TranslationServiceGrpcTransport, - transports.TranslationServiceGrpcAsyncIOTransport, + translation_service.DetectLanguageRequest, + dict, ], ) -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_detect_language_rest(request_type): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - ], -) -def test_transport_kind(transport_name): - transport = TranslationServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), + # 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 = translation_service.DetectLanguageResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = translation_service.DetectLanguageResponse.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.detect_language(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.DetectLanguageResponse) + + +def test_detect_language_rest_required_fields( + request_type=translation_service.DetectLanguageRequest, +): + transport_class = transports.TranslationServiceRestTransport + + 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, + ) ) - assert transport.kind == transport_name + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).detect_language._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() + ).detect_language._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" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = TranslationServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.TranslationServiceGrpcTransport, - ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = translation_service.DetectLanguageResponse() + # 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 = translation_service.DetectLanguageResponse.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 -def test_translation_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.TranslationServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + response = client.detect_language(request) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params -def test_translation_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.translate_v3beta1.services.translation_service.transports.TranslationServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.TranslationServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "translate_text", - "detect_language", - "get_supported_languages", - "translate_document", - "batch_translate_text", - "batch_translate_document", - "create_glossary", - "list_glossaries", - "get_glossary", - "delete_glossary", +def test_detect_language_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + unset_fields = transport.detect_language._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) -def test_translation_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_detect_language_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), + ) + client = TranslationServiceClient(transport=transport) with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.translate_v3beta1.services.translation_service.transports.TranslationServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TranslationServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.TranslationServiceRestInterceptor, "post_detect_language" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_detect_language" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.DetectLanguageRequest.pb( + translation_service.DetectLanguageRequest() ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-translation", - ), - quota_project_id="octopus", + 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 = translation_service.DetectLanguageResponse.to_json( + translation_service.DetectLanguageResponse() ) + request = translation_service.DetectLanguageRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = translation_service.DetectLanguageResponse() -def test_translation_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.translate_v3beta1.services.translation_service.transports.TranslationServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TranslationServiceTransport() - adc.assert_called_once() - - -def test_translation_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - TranslationServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-translation", - ), - quota_project_id=None, + client.detect_language( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() -@pytest.mark.parametrize( + +def test_detect_language_rest_bad_request( + transport: str = "rest", request_type=translation_service.DetectLanguageRequest +): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.detect_language(request) + + +def test_detect_language_rest_flattened(): + client = TranslationServiceClient( + 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 = translation_service.DetectLanguageResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + model="model_value", + mime_type="mime_type_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 = translation_service.DetectLanguageResponse.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.detect_language(**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/v3beta1/{parent=projects/*/locations/*}:detectLanguage" + % client.transport._host, + args[1], + ) + + +def test_detect_language_rest_flattened_error(transport: str = "rest"): + client = TranslationServiceClient( + 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.detect_language( + translation_service.DetectLanguageRequest(), + parent="parent_value", + model="model_value", + mime_type="mime_type_value", + ) + + +def test_detect_language_rest_error(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + translation_service.GetSupportedLanguagesRequest, + dict, + ], +) +def test_get_supported_languages_rest(request_type): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = translation_service.SupportedLanguages() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = translation_service.SupportedLanguages.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_supported_languages(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.SupportedLanguages) + + +def test_get_supported_languages_rest_required_fields( + request_type=translation_service.GetSupportedLanguagesRequest, +): + transport_class = transports.TranslationServiceRestTransport + + 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() + ).get_supported_languages._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() + ).get_supported_languages._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "display_language_code", + "model", + ) + ) + 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 = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = translation_service.SupportedLanguages() + # 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 = translation_service.SupportedLanguages.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_supported_languages(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_supported_languages_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_supported_languages._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "displayLanguageCode", + "model", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_supported_languages_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), + ) + client = TranslationServiceClient(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.TranslationServiceRestInterceptor, "post_get_supported_languages" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_get_supported_languages" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.GetSupportedLanguagesRequest.pb( + translation_service.GetSupportedLanguagesRequest() + ) + 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 = translation_service.SupportedLanguages.to_json( + translation_service.SupportedLanguages() + ) + + request = translation_service.GetSupportedLanguagesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = translation_service.SupportedLanguages() + + client.get_supported_languages( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_supported_languages_rest_bad_request( + transport: str = "rest", + request_type=translation_service.GetSupportedLanguagesRequest, +): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_supported_languages(request) + + +def test_get_supported_languages_rest_flattened(): + client = TranslationServiceClient( + 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 = translation_service.SupportedLanguages() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + display_language_code="display_language_code_value", + model="model_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 = translation_service.SupportedLanguages.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_supported_languages(**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/v3beta1/{parent=projects/*/locations/*}/supportedLanguages" + % client.transport._host, + args[1], + ) + + +def test_get_supported_languages_rest_flattened_error(transport: str = "rest"): + client = TranslationServiceClient( + 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_supported_languages( + translation_service.GetSupportedLanguagesRequest(), + parent="parent_value", + display_language_code="display_language_code_value", + model="model_value", + ) + + +def test_get_supported_languages_rest_error(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + translation_service.TranslateDocumentRequest, + dict, + ], +) +def test_translate_document_rest(request_type): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = translation_service.TranslateDocumentResponse( + model="model_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = translation_service.TranslateDocumentResponse.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.translate_document(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.TranslateDocumentResponse) + assert response.model == "model_value" + + +def test_translate_document_rest_required_fields( + request_type=translation_service.TranslateDocumentRequest, +): + transport_class = transports.TranslationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["target_language_code"] = "" + 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() + ).translate_document._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" + jsonified_request["targetLanguageCode"] = "target_language_code_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).translate_document._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" + assert "targetLanguageCode" in jsonified_request + assert jsonified_request["targetLanguageCode"] == "target_language_code_value" + + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = translation_service.TranslateDocumentResponse() + # 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 = translation_service.TranslateDocumentResponse.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.translate_document(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_translate_document_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.translate_document._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "targetLanguageCode", + "documentInputConfig", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_translate_document_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), + ) + client = TranslationServiceClient(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.TranslationServiceRestInterceptor, "post_translate_document" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_translate_document" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.TranslateDocumentRequest.pb( + translation_service.TranslateDocumentRequest() + ) + 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 = ( + translation_service.TranslateDocumentResponse.to_json( + translation_service.TranslateDocumentResponse() + ) + ) + + request = translation_service.TranslateDocumentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = translation_service.TranslateDocumentResponse() + + client.translate_document( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_translate_document_rest_bad_request( + transport: str = "rest", request_type=translation_service.TranslateDocumentRequest +): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.translate_document(request) + + +def test_translate_document_rest_error(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + translation_service.BatchTranslateTextRequest, + dict, + ], +) +def test_batch_translate_text_rest(request_type): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.batch_translate_text(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_batch_translate_text_rest_required_fields( + request_type=translation_service.BatchTranslateTextRequest, +): + transport_class = transports.TranslationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["source_language_code"] = "" + request_init["target_language_codes"] = "" + 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() + ).batch_translate_text._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" + jsonified_request["sourceLanguageCode"] = "source_language_code_value" + jsonified_request["targetLanguageCodes"] = "target_language_codes_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_translate_text._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" + assert "sourceLanguageCode" in jsonified_request + assert jsonified_request["sourceLanguageCode"] == "source_language_code_value" + assert "targetLanguageCodes" in jsonified_request + assert jsonified_request["targetLanguageCodes"] == "target_language_codes_value" + + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.batch_translate_text(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_batch_translate_text_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_translate_text._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "sourceLanguageCode", + "targetLanguageCodes", + "inputConfigs", + "outputConfig", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_translate_text_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), + ) + client = TranslationServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TranslationServiceRestInterceptor, "post_batch_translate_text" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_batch_translate_text" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.BatchTranslateTextRequest.pb( + translation_service.BatchTranslateTextRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = translation_service.BatchTranslateTextRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.batch_translate_text( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_translate_text_rest_bad_request( + transport: str = "rest", request_type=translation_service.BatchTranslateTextRequest +): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_translate_text(request) + + +def test_batch_translate_text_rest_error(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + translation_service.BatchTranslateDocumentRequest, + dict, + ], +) +def test_batch_translate_document_rest(request_type): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.batch_translate_document(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_batch_translate_document_rest_required_fields( + request_type=translation_service.BatchTranslateDocumentRequest, +): + transport_class = transports.TranslationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["source_language_code"] = "" + request_init["target_language_codes"] = "" + 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() + ).batch_translate_document._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" + jsonified_request["sourceLanguageCode"] = "source_language_code_value" + jsonified_request["targetLanguageCodes"] = "target_language_codes_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_translate_document._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" + assert "sourceLanguageCode" in jsonified_request + assert jsonified_request["sourceLanguageCode"] == "source_language_code_value" + assert "targetLanguageCodes" in jsonified_request + assert jsonified_request["targetLanguageCodes"] == "target_language_codes_value" + + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.batch_translate_document(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_batch_translate_document_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_translate_document._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "sourceLanguageCode", + "targetLanguageCodes", + "inputConfigs", + "outputConfig", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_translate_document_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), + ) + client = TranslationServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TranslationServiceRestInterceptor, "post_batch_translate_document" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_batch_translate_document" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.BatchTranslateDocumentRequest.pb( + translation_service.BatchTranslateDocumentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = translation_service.BatchTranslateDocumentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.batch_translate_document( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_translate_document_rest_bad_request( + transport: str = "rest", + request_type=translation_service.BatchTranslateDocumentRequest, +): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_translate_document(request) + + +def test_batch_translate_document_rest_flattened(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + source_language_code="source_language_code_value", + target_language_codes=["target_language_codes_value"], + input_configs=[ + translation_service.BatchDocumentInputConfig( + gcs_source=translation_service.GcsSource( + input_uri="input_uri_value" + ) + ) + ], + output_config=translation_service.BatchDocumentOutputConfig( + gcs_destination=translation_service.GcsDestination( + output_uri_prefix="output_uri_prefix_value" + ) + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.batch_translate_document(**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/v3beta1/{parent=projects/*/locations/*}:batchTranslateDocument" + % client.transport._host, + args[1], + ) + + +def test_batch_translate_document_rest_flattened_error(transport: str = "rest"): + client = TranslationServiceClient( + 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.batch_translate_document( + translation_service.BatchTranslateDocumentRequest(), + parent="parent_value", + source_language_code="source_language_code_value", + target_language_codes=["target_language_codes_value"], + input_configs=[ + translation_service.BatchDocumentInputConfig( + gcs_source=translation_service.GcsSource( + input_uri="input_uri_value" + ) + ) + ], + output_config=translation_service.BatchDocumentOutputConfig( + gcs_destination=translation_service.GcsDestination( + output_uri_prefix="output_uri_prefix_value" + ) + ), + ) + + +def test_batch_translate_document_rest_error(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + translation_service.CreateGlossaryRequest, + dict, + ], +) +def test_create_glossary_rest(request_type): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["glossary"] = { + "name": "name_value", + "language_pair": { + "source_language_code": "source_language_code_value", + "target_language_code": "target_language_code_value", + }, + "language_codes_set": { + "language_codes": ["language_codes_value1", "language_codes_value2"] + }, + "input_config": {"gcs_source": {"input_uri": "input_uri_value"}}, + "entry_count": 1210, + "submit_time": {"seconds": 751, "nanos": 543}, + "end_time": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_glossary(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_glossary_rest_required_fields( + request_type=translation_service.CreateGlossaryRequest, +): + transport_class = transports.TranslationServiceRestTransport + + 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() + ).create_glossary._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_glossary._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 = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_glossary(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_glossary_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_glossary._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "glossary", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_glossary_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), + ) + client = TranslationServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TranslationServiceRestInterceptor, "post_create_glossary" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_create_glossary" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.CreateGlossaryRequest.pb( + translation_service.CreateGlossaryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = translation_service.CreateGlossaryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_glossary( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_glossary_rest_bad_request( + transport: str = "rest", request_type=translation_service.CreateGlossaryRequest +): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["glossary"] = { + "name": "name_value", + "language_pair": { + "source_language_code": "source_language_code_value", + "target_language_code": "target_language_code_value", + }, + "language_codes_set": { + "language_codes": ["language_codes_value1", "language_codes_value2"] + }, + "input_config": {"gcs_source": {"input_uri": "input_uri_value"}}, + "entry_count": 1210, + "submit_time": {"seconds": 751, "nanos": 543}, + "end_time": {}, + } + 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.create_glossary(request) + + +def test_create_glossary_rest_flattened(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + glossary=translation_service.Glossary(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_glossary(**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/v3beta1/{parent=projects/*/locations/*}/glossaries" + % client.transport._host, + args[1], + ) + + +def test_create_glossary_rest_flattened_error(transport: str = "rest"): + client = TranslationServiceClient( + 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.create_glossary( + translation_service.CreateGlossaryRequest(), + parent="parent_value", + glossary=translation_service.Glossary(name="name_value"), + ) + + +def test_create_glossary_rest_error(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + translation_service.ListGlossariesRequest, + dict, + ], +) +def test_list_glossaries_rest(request_type): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = translation_service.ListGlossariesResponse( + 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 = translation_service.ListGlossariesResponse.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_glossaries(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGlossariesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_glossaries_rest_required_fields( + request_type=translation_service.ListGlossariesRequest, +): + transport_class = transports.TranslationServiceRestTransport + + 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_glossaries._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_glossaries._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = translation_service.ListGlossariesResponse() + # 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 = translation_service.ListGlossariesResponse.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_glossaries(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_glossaries_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_glossaries._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_glossaries_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), + ) + client = TranslationServiceClient(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.TranslationServiceRestInterceptor, "post_list_glossaries" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_list_glossaries" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.ListGlossariesRequest.pb( + translation_service.ListGlossariesRequest() + ) + 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 = translation_service.ListGlossariesResponse.to_json( + translation_service.ListGlossariesResponse() + ) + + request = translation_service.ListGlossariesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = translation_service.ListGlossariesResponse() + + client.list_glossaries( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_glossaries_rest_bad_request( + transport: str = "rest", request_type=translation_service.ListGlossariesRequest +): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_glossaries(request) + + +def test_list_glossaries_rest_flattened(): + client = TranslationServiceClient( + 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 = translation_service.ListGlossariesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + filter="filter_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 = translation_service.ListGlossariesResponse.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_glossaries(**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/v3beta1/{parent=projects/*/locations/*}/glossaries" + % client.transport._host, + args[1], + ) + + +def test_list_glossaries_rest_flattened_error(transport: str = "rest"): + client = TranslationServiceClient( + 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_glossaries( + translation_service.ListGlossariesRequest(), + parent="parent_value", + filter="filter_value", + ) + + +def test_list_glossaries_rest_pager(transport: str = "rest"): + client = TranslationServiceClient( + 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 = ( + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + translation_service.Glossary(), + ], + next_page_token="abc", + ), + translation_service.ListGlossariesResponse( + glossaries=[], + next_page_token="def", + ), + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + ], + next_page_token="ghi", + ), + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + translation_service.ListGlossariesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_glossaries(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, translation_service.Glossary) for i in results) + + pages = list(client.list_glossaries(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", + [ + translation_service.GetGlossaryRequest, + dict, + ], +) +def test_get_glossary_rest(request_type): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/glossaries/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = translation_service.Glossary( + name="name_value", + entry_count=1210, + language_pair=translation_service.Glossary.LanguageCodePair( + source_language_code="source_language_code_value" + ), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = translation_service.Glossary.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_glossary(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.Glossary) + assert response.name == "name_value" + assert response.entry_count == 1210 + + +def test_get_glossary_rest_required_fields( + request_type=translation_service.GetGlossaryRequest, +): + transport_class = transports.TranslationServiceRestTransport + + 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_glossary._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_glossary._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 = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = translation_service.Glossary() + # 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 = translation_service.Glossary.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_glossary(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_glossary_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_glossary._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_glossary_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), + ) + client = TranslationServiceClient(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.TranslationServiceRestInterceptor, "post_get_glossary" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_get_glossary" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.GetGlossaryRequest.pb( + translation_service.GetGlossaryRequest() + ) + 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 = translation_service.Glossary.to_json( + translation_service.Glossary() + ) + + request = translation_service.GetGlossaryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = translation_service.Glossary() + + client.get_glossary( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_glossary_rest_bad_request( + transport: str = "rest", request_type=translation_service.GetGlossaryRequest +): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/glossaries/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_glossary(request) + + +def test_get_glossary_rest_flattened(): + client = TranslationServiceClient( + 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 = translation_service.Glossary() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/glossaries/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = translation_service.Glossary.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_glossary(**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/v3beta1/{name=projects/*/locations/*/glossaries/*}" + % client.transport._host, + args[1], + ) + + +def test_get_glossary_rest_flattened_error(transport: str = "rest"): + client = TranslationServiceClient( + 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_glossary( + translation_service.GetGlossaryRequest(), + name="name_value", + ) + + +def test_get_glossary_rest_error(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + translation_service.DeleteGlossaryRequest, + dict, + ], +) +def test_delete_glossary_rest(request_type): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/glossaries/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_glossary(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_glossary_rest_required_fields( + request_type=translation_service.DeleteGlossaryRequest, +): + transport_class = transports.TranslationServiceRestTransport + + 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_glossary._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_glossary._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 = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_glossary(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_glossary_rest_unset_required_fields(): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_glossary._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_glossary_rest_interceptors(null_interceptor): + transport = transports.TranslationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TranslationServiceRestInterceptor(), + ) + client = TranslationServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TranslationServiceRestInterceptor, "post_delete_glossary" + ) as post, mock.patch.object( + transports.TranslationServiceRestInterceptor, "pre_delete_glossary" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = translation_service.DeleteGlossaryRequest.pb( + translation_service.DeleteGlossaryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = translation_service.DeleteGlossaryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_glossary( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_glossary_rest_bad_request( + transport: str = "rest", request_type=translation_service.DeleteGlossaryRequest +): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/glossaries/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_glossary(request) + + +def test_delete_glossary_rest_flattened(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/glossaries/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_glossary(**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/v3beta1/{name=projects/*/locations/*/glossaries/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_glossary_rest_flattened_error(transport: str = "rest"): + client = TranslationServiceClient( + 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_glossary( + translation_service.DeleteGlossaryRequest(), + name="name_value", + ) + + +def test_delete_glossary_rest_error(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TranslationServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TranslationServiceClient( + 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 = TranslationServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TranslationServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TranslationServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TranslationServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TranslationServiceGrpcTransport, + transports.TranslationServiceGrpcAsyncIOTransport, + transports.TranslationServiceRestTransport, + ], +) +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 = TranslationServiceClient.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 = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.TranslationServiceGrpcTransport, + ) + + +def test_translation_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.TranslationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_translation_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.translate_v3beta1.services.translation_service.transports.TranslationServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.TranslationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "translate_text", + "detect_language", + "get_supported_languages", + "translate_document", + "batch_translate_text", + "batch_translate_document", + "create_glossary", + "list_glossaries", + "get_glossary", + "delete_glossary", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_translation_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.translate_v3beta1.services.translation_service.transports.TranslationServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TranslationServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + quota_project_id="octopus", + ) + + +def test_translation_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.translate_v3beta1.services.translation_service.transports.TranslationServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TranslationServiceTransport() + adc.assert_called_once() + + +def test_translation_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + TranslationServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( "transport_class", [ transports.TranslationServiceGrpcTransport, @@ -3395,6 +6178,7 @@ def test_translation_service_transport_auth_adc(transport_class): [ transports.TranslationServiceGrpcTransport, transports.TranslationServiceGrpcAsyncIOTransport, + transports.TranslationServiceRestTransport, ], ) def test_translation_service_transport_auth_gdch_credentials(transport_class): @@ -3497,11 +6281,40 @@ def test_translation_service_grpc_transport_client_cert_source_for_mtls( ) +def test_translation_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.TranslationServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_translation_service_rest_lro_client(): + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_translation_service_host_no_port(transport_name): @@ -3512,7 +6325,11 @@ def test_translation_service_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("translate.googleapis.com:443") + assert client.transport._host == ( + "translate.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://translate.googleapis.com" + ) @pytest.mark.parametrize( @@ -3520,6 +6337,7 @@ def test_translation_service_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_translation_service_host_with_port(transport_name): @@ -3530,7 +6348,60 @@ def test_translation_service_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("translate.googleapis.com:8000") + assert client.transport._host == ( + "translate.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://translate.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_translation_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = TranslationServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = TranslationServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.translate_text._session + session2 = client2.transport.translate_text._session + assert session1 != session2 + session1 = client1.transport.detect_language._session + session2 = client2.transport.detect_language._session + assert session1 != session2 + session1 = client1.transport.get_supported_languages._session + session2 = client2.transport.get_supported_languages._session + assert session1 != session2 + session1 = client1.transport.translate_document._session + session2 = client2.transport.translate_document._session + assert session1 != session2 + session1 = client1.transport.batch_translate_text._session + session2 = client2.transport.batch_translate_text._session + assert session1 != session2 + session1 = client1.transport.batch_translate_document._session + session2 = client2.transport.batch_translate_document._session + assert session1 != session2 + session1 = client1.transport.create_glossary._session + session2 = client2.transport.create_glossary._session + assert session1 != session2 + session1 = client1.transport.list_glossaries._session + session2 = client2.transport.list_glossaries._session + assert session1 != session2 + session1 = client1.transport.get_glossary._session + session2 = client2.transport.get_glossary._session + assert session1 != session2 + session1 = client1.transport.delete_glossary._session + session2 = client2.transport.delete_glossary._session + assert session1 != session2 def test_translation_service_grpc_transport_channel(): @@ -3861,6 +6732,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -3878,6 +6750,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/translation-v3beta1-py.tar.gz b/translation-v3beta1-py.tar.gz new file mode 100644 index 00000000..95fbe361 Binary files /dev/null and b/translation-v3beta1-py.tar.gz differ