From 959a35c85e32867ed63c63d96593a240a5e8a1c4 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 20 May 2021 17:41:27 -0600 Subject: [PATCH] chore: upgrade gapic-generator-python to 0.46.3 (#158) fix: add async client to %name_%version/init.py chore: add autogenerated snippets chore: remove auth, policy, and options from the reserved names list feat: support self-signed JWT flow for service accounts chore: enable GAPIC metadata generation chore: sort subpackages in %namespace/%name/init.py fix(deps): add packaging requirement --- docs/translate_v3/translation_service.rst | 1 - .../translate_v3beta1/translation_service.rst | 1 - google/cloud/translate/__init__.py | 16 +- google/cloud/translate_v3/__init__.py | 7 +- google/cloud/translate_v3/gapic_metadata.json | 103 +++ .../cloud/translate_v3/services/__init__.py | 1 - .../services/translation_service/__init__.py | 2 - .../translation_service/async_client.py | 55 +- .../services/translation_service/client.py | 86 +-- .../services/translation_service/pagers.py | 4 +- .../transports/__init__.py | 2 - .../translation_service/transports/base.py | 154 +++-- .../translation_service/transports/grpc.py | 40 +- .../transports/grpc_asyncio.py | 38 +- google/cloud/translate_v3/types/__init__.py | 2 - .../translate_v3/types/translation_service.py | 214 ++---- google/cloud/translate_v3beta1/__init__.py | 7 +- .../translate_v3beta1/gapic_metadata.json | 123 ++++ .../translate_v3beta1/services/__init__.py | 1 - .../services/translation_service/__init__.py | 2 - .../translation_service/async_client.py | 58 +- .../services/translation_service/client.py | 89 +-- .../services/translation_service/pagers.py | 4 +- .../transports/__init__.py | 2 - .../translation_service/transports/base.py | 164 +++-- .../translation_service/transports/grpc.py | 44 +- .../transports/grpc_asyncio.py | 42 +- .../cloud/translate_v3beta1/types/__init__.py | 2 - .../types/translation_service.py | 334 +++------ scripts/fixup_translate_v3_keywords.py | 21 +- scripts/fixup_translate_v3beta1_keywords.py | 25 +- setup.py | 1 + testing/constraints-3.6.txt | 2 + tests/__init__.py | 15 + tests/unit/__init__.py | 15 + tests/unit/gapic/__init__.py | 15 + tests/unit/gapic/translate_v3/__init__.py | 1 - .../translate_v3/test_translation_service.py | 622 ++++++++++------- .../unit/gapic/translate_v3beta1/__init__.py | 1 - .../test_translation_service.py | 642 +++++++++++------- 40 files changed, 1682 insertions(+), 1276 deletions(-) create mode 100644 google/cloud/translate_v3/gapic_metadata.json create mode 100644 google/cloud/translate_v3beta1/gapic_metadata.json create mode 100644 tests/unit/__init__.py create mode 100644 tests/unit/gapic/__init__.py diff --git a/docs/translate_v3/translation_service.rst b/docs/translate_v3/translation_service.rst index 0a3597fd..e440fb5e 100644 --- a/docs/translate_v3/translation_service.rst +++ b/docs/translate_v3/translation_service.rst @@ -5,7 +5,6 @@ TranslationService :members: :inherited-members: - .. automodule:: google.cloud.translate_v3.services.translation_service.pagers :members: :inherited-members: diff --git a/docs/translate_v3beta1/translation_service.rst b/docs/translate_v3beta1/translation_service.rst index cfe3524b..743d0126 100644 --- a/docs/translate_v3beta1/translation_service.rst +++ b/docs/translate_v3beta1/translation_service.rst @@ -5,7 +5,6 @@ TranslationService :members: :inherited-members: - .. automodule:: google.cloud.translate_v3beta1.services.translation_service.pagers :members: :inherited-members: diff --git a/google/cloud/translate/__init__.py b/google/cloud/translate/__init__.py index 8c9024db..1597f753 100644 --- a/google/cloud/translate/__init__.py +++ b/google/cloud/translate/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,12 +14,13 @@ # limitations under the License. # -from google.cloud.translate_v3.services.translation_service.async_client import ( - TranslationServiceAsyncClient, -) from google.cloud.translate_v3.services.translation_service.client import ( TranslationServiceClient, ) +from google.cloud.translate_v3.services.translation_service.async_client import ( + TranslationServiceAsyncClient, +) + from google.cloud.translate_v3.types.translation_service import BatchTranslateMetadata from google.cloud.translate_v3.types.translation_service import BatchTranslateResponse from google.cloud.translate_v3.types.translation_service import ( @@ -31,9 +31,9 @@ from google.cloud.translate_v3.types.translation_service import DeleteGlossaryMetadata from google.cloud.translate_v3.types.translation_service import DeleteGlossaryRequest from google.cloud.translate_v3.types.translation_service import DeleteGlossaryResponse +from google.cloud.translate_v3.types.translation_service import DetectedLanguage from google.cloud.translate_v3.types.translation_service import DetectLanguageRequest from google.cloud.translate_v3.types.translation_service import DetectLanguageResponse -from google.cloud.translate_v3.types.translation_service import DetectedLanguage from google.cloud.translate_v3.types.translation_service import GcsDestination from google.cloud.translate_v3.types.translation_service import GcsSource from google.cloud.translate_v3.types.translation_service import GetGlossaryRequest @@ -56,6 +56,8 @@ from google.cloud.translate_v3.types.translation_service import Translation __all__ = ( + "TranslationServiceClient", + "TranslationServiceAsyncClient", "BatchTranslateMetadata", "BatchTranslateResponse", "BatchTranslateTextRequest", @@ -64,9 +66,9 @@ "DeleteGlossaryMetadata", "DeleteGlossaryRequest", "DeleteGlossaryResponse", + "DetectedLanguage", "DetectLanguageRequest", "DetectLanguageResponse", - "DetectedLanguage", "GcsDestination", "GcsSource", "GetGlossaryRequest", @@ -83,6 +85,4 @@ "TranslateTextRequest", "TranslateTextResponse", "Translation", - "TranslationServiceAsyncClient", - "TranslationServiceClient", ) diff --git a/google/cloud/translate_v3/__init__.py b/google/cloud/translate_v3/__init__.py index b7cd2fe0..29b7e63d 100644 --- a/google/cloud/translate_v3/__init__.py +++ b/google/cloud/translate_v3/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,6 +15,8 @@ # from .services.translation_service import TranslationServiceClient +from .services.translation_service import TranslationServiceAsyncClient + from .types.translation_service import BatchTranslateMetadata from .types.translation_service import BatchTranslateResponse from .types.translation_service import BatchTranslateTextRequest @@ -24,9 +25,9 @@ from .types.translation_service import DeleteGlossaryMetadata from .types.translation_service import DeleteGlossaryRequest from .types.translation_service import DeleteGlossaryResponse +from .types.translation_service import DetectedLanguage from .types.translation_service import DetectLanguageRequest from .types.translation_service import DetectLanguageResponse -from .types.translation_service import DetectedLanguage from .types.translation_service import GcsDestination from .types.translation_service import GcsSource from .types.translation_service import GetGlossaryRequest @@ -44,8 +45,8 @@ from .types.translation_service import TranslateTextResponse from .types.translation_service import Translation - __all__ = ( + "TranslationServiceAsyncClient", "BatchTranslateMetadata", "BatchTranslateResponse", "BatchTranslateTextRequest", diff --git a/google/cloud/translate_v3/gapic_metadata.json b/google/cloud/translate_v3/gapic_metadata.json new file mode 100644 index 00000000..4f16d870 --- /dev/null +++ b/google/cloud/translate_v3/gapic_metadata.json @@ -0,0 +1,103 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.translate_v3", + "protoPackage": "google.cloud.translation.v3", + "schema": "1.0", + "services": { + "TranslationService": { + "clients": { + "grpc": { + "libraryClient": "TranslationServiceClient", + "rpcs": { + "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" + ] + }, + "TranslateText": { + "methods": [ + "translate_text" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TranslationServiceAsyncClient", + "rpcs": { + "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" + ] + }, + "TranslateText": { + "methods": [ + "translate_text" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/translate_v3/services/__init__.py b/google/cloud/translate_v3/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/translate_v3/services/__init__.py +++ b/google/cloud/translate_v3/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/translate_v3/services/translation_service/__init__.py b/google/cloud/translate_v3/services/translation_service/__init__.py index e2442711..6d42bf0e 100644 --- a/google/cloud/translate_v3/services/translation_service/__init__.py +++ b/google/cloud/translate_v3/services/translation_service/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import TranslationServiceClient from .async_client import TranslationServiceAsyncClient 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 d293e203..c6c8e37b 100644 --- a/google/cloud/translate_v3/services/translation_service/async_client.py +++ b/google/cloud/translate_v3/services/translation_service/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,18 +20,17 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.translate_v3.services.translation_service import pagers from google.cloud.translate_v3.types import translation_service -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import TranslationServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import TranslationServiceGrpcAsyncIOTransport from .client import TranslationServiceClient @@ -49,31 +46,26 @@ class TranslationServiceAsyncClient: glossary_path = staticmethod(TranslationServiceClient.glossary_path) parse_glossary_path = staticmethod(TranslationServiceClient.parse_glossary_path) - common_billing_account_path = staticmethod( TranslationServiceClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( TranslationServiceClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(TranslationServiceClient.common_folder_path) parse_common_folder_path = staticmethod( TranslationServiceClient.parse_common_folder_path ) - common_organization_path = staticmethod( TranslationServiceClient.common_organization_path ) parse_common_organization_path = staticmethod( TranslationServiceClient.parse_common_organization_path ) - common_project_path = staticmethod(TranslationServiceClient.common_project_path) parse_common_project_path = staticmethod( TranslationServiceClient.parse_common_project_path ) - common_location_path = staticmethod(TranslationServiceClient.common_location_path) parse_common_location_path = staticmethod( TranslationServiceClient.parse_common_location_path @@ -81,7 +73,8 @@ class TranslationServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -96,7 +89,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -113,7 +106,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TranslationServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: TranslationServiceTransport: The transport used by the client instance. @@ -128,12 +121,12 @@ def transport(self) -> TranslationServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, TranslationServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the translation service client. + """Instantiates the translation service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -165,7 +158,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = TranslationServiceClient( credentials=credentials, transport=transport, @@ -277,7 +269,6 @@ async def translate_text( This corresponds to the ``source_language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -311,7 +302,6 @@ async def translate_text( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if target_language_code is not None: @@ -322,7 +312,6 @@ async def translate_text( request.mime_type = mime_type if source_language_code is not None: request.source_language_code = source_language_code - if contents: request.contents.extend(contents) @@ -414,7 +403,6 @@ async def detect_language( This corresponds to the ``content`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -441,7 +429,6 @@ async def detect_language( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if model is not None: @@ -538,7 +525,6 @@ async def get_supported_languages( This corresponds to the ``display_language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -565,7 +551,6 @@ async def get_supported_languages( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if model is not None: @@ -582,7 +567,8 @@ async def get_supported_languages( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -623,7 +609,6 @@ async def batch_translate_text( Args: request (:class:`google.cloud.translate_v3.types.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. @@ -641,7 +626,6 @@ async def batch_translate_text( """ # Create or coerce a protobuf request object. - request = translation_service.BatchTranslateTextRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -698,7 +682,6 @@ async def create_glossary( This corresponds to the ``glossary`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -728,7 +711,6 @@ async def create_glossary( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if glossary is not None: @@ -785,7 +767,6 @@ async def list_glossaries( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -814,7 +795,6 @@ async def list_glossaries( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -827,7 +807,8 @@ async def list_glossaries( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -875,7 +856,6 @@ async def get_glossary( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -902,7 +882,6 @@ async def get_glossary( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -915,7 +894,8 @@ async def get_glossary( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -958,7 +938,6 @@ async def delete_glossary( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -988,7 +967,6 @@ async def delete_glossary( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1001,7 +979,8 @@ async def delete_glossary( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), diff --git a/google/cloud/translate_v3/services/translation_service/client.py b/google/cloud/translate_v3/services/translation_service/client.py index c4637e75..11b26cd5 100644 --- a/google/cloud/translate_v3/services/translation_service/client.py +++ b/google/cloud/translate_v3/services/translation_service/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -36,8 +34,7 @@ from google.api_core import operation_async # type: ignore from google.cloud.translate_v3.services.translation_service import pagers from google.cloud.translate_v3.types import translation_service -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import TranslationServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import TranslationServiceGrpcTransport from .transports.grpc_asyncio import TranslationServiceGrpcAsyncIOTransport @@ -60,7 +57,7 @@ class TranslationServiceClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[TranslationServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -83,7 +80,8 @@ class TranslationServiceClient(metaclass=TranslationServiceClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -117,7 +115,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -134,7 +133,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -153,23 +152,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TranslationServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - TranslationServiceTransport: The transport used by the client instance. + TranslationServiceTransport: The transport used by the client + instance. """ return self._transport @staticmethod def glossary_path(project: str, location: str, glossary: str,) -> str: - """Return a fully-qualified glossary string.""" + """Returns a fully-qualified glossary string.""" return "projects/{project}/locations/{location}/glossaries/{glossary}".format( project=project, location=location, glossary=glossary, ) @staticmethod def parse_glossary_path(path: str) -> Dict[str, str]: - """Parse a glossary path into its component segments.""" + """Parses a glossary path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/glossaries/(?P.+?)$", path, @@ -178,7 +178,7 @@ def parse_glossary_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -191,7 +191,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -202,7 +202,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -213,7 +213,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -224,7 +224,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -238,12 +238,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, TranslationServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the translation service client. + """Instantiates the translation service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -298,9 +298,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -312,12 +313,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -332,8 +335,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -452,7 +455,6 @@ def translate_text( This corresponds to the ``source_language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -488,10 +490,8 @@ def translate_text( # there are no flattened fields. if not isinstance(request, translation_service.TranslateTextRequest): request = translation_service.TranslateTextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if target_language_code is not None: @@ -589,7 +589,6 @@ def detect_language( This corresponds to the ``content`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -618,10 +617,8 @@ def detect_language( # there are no flattened fields. if not isinstance(request, translation_service.DetectLanguageRequest): request = translation_service.DetectLanguageRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if model is not None: @@ -714,7 +711,6 @@ def get_supported_languages( This corresponds to the ``display_language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -743,10 +739,8 @@ def get_supported_languages( # there are no flattened fields. if not isinstance(request, translation_service.GetSupportedLanguagesRequest): request = translation_service.GetSupportedLanguagesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if model is not None: @@ -791,7 +785,6 @@ def batch_translate_text( Args: request (google.cloud.translate_v3.types.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. @@ -809,7 +802,6 @@ def batch_translate_text( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a translation_service.BatchTranslateTextRequest. # There's no risk of modifying the input as we've already verified @@ -867,7 +859,6 @@ def create_glossary( This corresponds to the ``glossary`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -899,10 +890,8 @@ def create_glossary( # there are no flattened fields. if not isinstance(request, translation_service.CreateGlossaryRequest): request = translation_service.CreateGlossaryRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if glossary is not None: @@ -955,7 +944,6 @@ def list_glossaries( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -986,10 +974,8 @@ def list_glossaries( # there are no flattened fields. if not isinstance(request, translation_service.ListGlossariesRequest): request = translation_service.ListGlossariesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1037,7 +1023,6 @@ def get_glossary( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1066,10 +1051,8 @@ def get_glossary( # there are no flattened fields. if not isinstance(request, translation_service.GetGlossaryRequest): request = translation_service.GetGlossaryRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1112,7 +1095,6 @@ def delete_glossary( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1144,10 +1126,8 @@ def delete_glossary( # there are no flattened fields. if not isinstance(request, translation_service.DeleteGlossaryRequest): request = translation_service.DeleteGlossaryRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/translate_v3/services/translation_service/pagers.py b/google/cloud/translate_v3/services/translation_service/pagers.py index d6d24694..c00ac6ac 100644 --- a/google/cloud/translate_v3/services/translation_service/pagers.py +++ b/google/cloud/translate_v3/services/translation_service/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and 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 92859637..11cb0a7d 100644 --- a/google/cloud/translate_v3/services/translation_service/transports/__init__.py +++ b/google/cloud/translate_v3/services/translation_service/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/translate_v3/services/translation_service/transports/base.py b/google/cloud/translate_v3/services/translation_service/transports/base.py index 1107abf8..88bd4fb0 100644 --- a/google/cloud/translate_v3/services/translation_service/transports/base.py +++ b/google/cloud/translate_v3/services/translation_service/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.translate_v3.types import translation_service -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -37,6 +36,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class TranslationServiceTransport(abc.ABC): """Abstract transport class for TranslationService.""" @@ -46,21 +56,24 @@ class TranslationServiceTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-translation", ) + DEFAULT_HOST: str = "translate.googleapis.com" + def __init__( self, *, - host: str = "translate.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -69,7 +82,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -83,29 +96,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -122,7 +182,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -144,7 +205,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -158,7 +220,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -172,7 +235,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -189,11 +253,11 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def translate_text( self, - ) -> typing.Callable[ + ) -> Callable[ [translation_service.TranslateTextRequest], - typing.Union[ + Union[ translation_service.TranslateTextResponse, - typing.Awaitable[translation_service.TranslateTextResponse], + Awaitable[translation_service.TranslateTextResponse], ], ]: raise NotImplementedError() @@ -201,11 +265,11 @@ def translate_text( @property def detect_language( self, - ) -> typing.Callable[ + ) -> Callable[ [translation_service.DetectLanguageRequest], - typing.Union[ + Union[ translation_service.DetectLanguageResponse, - typing.Awaitable[translation_service.DetectLanguageResponse], + Awaitable[translation_service.DetectLanguageResponse], ], ]: raise NotImplementedError() @@ -213,11 +277,11 @@ def detect_language( @property def get_supported_languages( self, - ) -> typing.Callable[ + ) -> Callable[ [translation_service.GetSupportedLanguagesRequest], - typing.Union[ + Union[ translation_service.SupportedLanguages, - typing.Awaitable[translation_service.SupportedLanguages], + Awaitable[translation_service.SupportedLanguages], ], ]: raise NotImplementedError() @@ -225,29 +289,29 @@ def get_supported_languages( @property def batch_translate_text( self, - ) -> typing.Callable[ + ) -> Callable[ [translation_service.BatchTranslateTextRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def create_glossary( self, - ) -> typing.Callable[ + ) -> Callable[ [translation_service.CreateGlossaryRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def list_glossaries( self, - ) -> typing.Callable[ + ) -> Callable[ [translation_service.ListGlossariesRequest], - typing.Union[ + Union[ translation_service.ListGlossariesResponse, - typing.Awaitable[translation_service.ListGlossariesResponse], + Awaitable[translation_service.ListGlossariesResponse], ], ]: raise NotImplementedError() @@ -255,20 +319,18 @@ def list_glossaries( @property def get_glossary( self, - ) -> typing.Callable[ + ) -> Callable[ [translation_service.GetGlossaryRequest], - typing.Union[ - translation_service.Glossary, typing.Awaitable[translation_service.Glossary] - ], + Union[translation_service.Glossary, Awaitable[translation_service.Glossary]], ]: raise NotImplementedError() @property def delete_glossary( self, - ) -> typing.Callable[ + ) -> Callable[ [translation_service.DeleteGlossaryRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/translate_v3/services/translation_service/transports/grpc.py b/google/cloud/translate_v3/services/translation_service/transports/grpc.py index 2e0a86b0..4b0bfadd 100644 --- a/google/cloud/translate_v3/services/translation_service/transports/grpc.py +++ b/google/cloud/translate_v3/services/translation_service/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.translate_v3.types import translation_service -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import TranslationServiceTransport, DEFAULT_CLIENT_INFO @@ -52,7 +49,7 @@ def __init__( self, *, host: str = "translate.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -66,7 +63,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -177,7 +175,7 @@ def __init__( def create_channel( cls, host: str = "translate.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -208,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -330,7 +330,7 @@ def get_supported_languages( def batch_translate_text( self, ) -> Callable[ - [translation_service.BatchTranslateTextRequest], operations.Operation + [translation_service.BatchTranslateTextRequest], operations_pb2.Operation ]: r"""Return a callable for the batch translate text method over gRPC. @@ -358,14 +358,16 @@ def batch_translate_text( self._stubs["batch_translate_text"] = self.grpc_channel.unary_unary( "/google.cloud.translation.v3.TranslationService/BatchTranslateText", request_serializer=translation_service.BatchTranslateTextRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_translate_text"] @property def create_glossary( self, - ) -> Callable[[translation_service.CreateGlossaryRequest], operations.Operation]: + ) -> Callable[ + [translation_service.CreateGlossaryRequest], operations_pb2.Operation + ]: r"""Return a callable for the create glossary method over gRPC. Creates a glossary and returns the long-running operation. @@ -385,7 +387,7 @@ def create_glossary( self._stubs["create_glossary"] = self.grpc_channel.unary_unary( "/google.cloud.translation.v3.TranslationService/CreateGlossary", request_serializer=translation_service.CreateGlossaryRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_glossary"] @@ -451,7 +453,9 @@ def get_glossary( @property def delete_glossary( self, - ) -> Callable[[translation_service.DeleteGlossaryRequest], operations.Operation]: + ) -> Callable[ + [translation_service.DeleteGlossaryRequest], operations_pb2.Operation + ]: r"""Return a callable for the delete glossary method over gRPC. Deletes a glossary, or cancels glossary construction if the @@ -472,7 +476,7 @@ def delete_glossary( self._stubs["delete_glossary"] = self.grpc_channel.unary_unary( "/google.cloud.translation.v3.TranslationService/DeleteGlossary", request_serializer=translation_service.DeleteGlossaryRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_glossary"] diff --git a/google/cloud/translate_v3/services/translation_service/transports/grpc_asyncio.py b/google/cloud/translate_v3/services/translation_service/transports/grpc_asyncio.py index 442b84dc..af684004 100644 --- a/google/cloud/translate_v3/services/translation_service/transports/grpc_asyncio.py +++ b/google/cloud/translate_v3/services/translation_service/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.translate_v3.types import translation_service -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import TranslationServiceTransport, DEFAULT_CLIENT_INFO from .grpc import TranslationServiceGrpcTransport @@ -55,7 +52,7 @@ class TranslationServiceGrpcAsyncIOTransport(TranslationServiceTransport): def create_channel( cls, host: str = "translate.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -82,13 +79,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -96,7 +95,7 @@ def __init__( self, *, host: str = "translate.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -110,7 +109,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -169,7 +169,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -336,7 +335,8 @@ def get_supported_languages( def batch_translate_text( self, ) -> Callable[ - [translation_service.BatchTranslateTextRequest], Awaitable[operations.Operation] + [translation_service.BatchTranslateTextRequest], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the batch translate text method over gRPC. @@ -364,7 +364,7 @@ def batch_translate_text( self._stubs["batch_translate_text"] = self.grpc_channel.unary_unary( "/google.cloud.translation.v3.TranslationService/BatchTranslateText", request_serializer=translation_service.BatchTranslateTextRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_translate_text"] @@ -372,7 +372,7 @@ def batch_translate_text( def create_glossary( self, ) -> Callable[ - [translation_service.CreateGlossaryRequest], Awaitable[operations.Operation] + [translation_service.CreateGlossaryRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the create glossary method over gRPC. @@ -393,7 +393,7 @@ def create_glossary( self._stubs["create_glossary"] = self.grpc_channel.unary_unary( "/google.cloud.translation.v3.TranslationService/CreateGlossary", request_serializer=translation_service.CreateGlossaryRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_glossary"] @@ -461,7 +461,7 @@ def get_glossary( def delete_glossary( self, ) -> Callable[ - [translation_service.DeleteGlossaryRequest], Awaitable[operations.Operation] + [translation_service.DeleteGlossaryRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the delete glossary method over gRPC. @@ -483,7 +483,7 @@ def delete_glossary( self._stubs["delete_glossary"] = self.grpc_channel.unary_unary( "/google.cloud.translation.v3.TranslationService/DeleteGlossary", request_serializer=translation_service.DeleteGlossaryRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_glossary"] diff --git a/google/cloud/translate_v3/types/__init__.py b/google/cloud/translate_v3/types/__init__.py index 98fddfeb..fe8f13de 100644 --- a/google/cloud/translate_v3/types/__init__.py +++ b/google/cloud/translate_v3/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .translation_service import ( BatchTranslateMetadata, BatchTranslateResponse, diff --git a/google/cloud/translate_v3/types/translation_service.py b/google/cloud/translate_v3/types/translation_service.py index 3740856f..7ff7720b 100644 --- a/google/cloud/translate_v3/types/translation_service.py +++ b/google/cloud/translate_v3/types/translation_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -68,14 +65,12 @@ class TranslateTextGlossaryConfig(proto.Message): nsensitive. Default value is false if missing. """ - glossary = proto.Field(proto.STRING, number=1) - - ignore_case = proto.Field(proto.BOOL, number=2) + glossary = proto.Field(proto.STRING, number=1,) + ignore_case = proto.Field(proto.BOOL, number=2,) class TranslateTextRequest(proto.Message): r"""The request message for synchronous translation. - Attributes: contents (Sequence[str]): Required. The content of the input in string @@ -152,28 +147,20 @@ class TranslateTextRequest(proto.Message): for more information. """ - contents = proto.RepeatedField(proto.STRING, number=1) - - mime_type = proto.Field(proto.STRING, number=3) - - source_language_code = proto.Field(proto.STRING, number=4) - - target_language_code = proto.Field(proto.STRING, number=5) - - parent = proto.Field(proto.STRING, number=8) - - model = proto.Field(proto.STRING, number=6) - + contents = proto.RepeatedField(proto.STRING, number=1,) + mime_type = proto.Field(proto.STRING, number=3,) + source_language_code = proto.Field(proto.STRING, number=4,) + target_language_code = proto.Field(proto.STRING, number=5,) + parent = proto.Field(proto.STRING, number=8,) + model = proto.Field(proto.STRING, number=6,) glossary_config = proto.Field( proto.MESSAGE, number=7, message="TranslateTextGlossaryConfig", ) - - labels = proto.MapField(proto.STRING, proto.STRING, number=10) + labels = proto.MapField(proto.STRING, proto.STRING, number=10,) class TranslateTextResponse(proto.Message): r""" - Attributes: translations (Sequence[google.cloud.translate_v3.types.Translation]): Text translation responses with no glossary applied. This @@ -188,7 +175,6 @@ class TranslateTextResponse(proto.Message): """ translations = proto.RepeatedField(proto.MESSAGE, number=1, message="Translation",) - glossary_translations = proto.RepeatedField( proto.MESSAGE, number=3, message="Translation", ) @@ -196,7 +182,6 @@ class TranslateTextResponse(proto.Message): class Translation(proto.Message): r"""A single translation response. - Attributes: translated_text (str): Text translated into the target language. @@ -220,12 +205,9 @@ class Translation(proto.Message): The ``glossary_config`` used for this translation. """ - translated_text = proto.Field(proto.STRING, number=1) - - model = proto.Field(proto.STRING, number=2) - - detected_language_code = proto.Field(proto.STRING, number=4) - + translated_text = proto.Field(proto.STRING, number=1,) + model = proto.Field(proto.STRING, number=2,) + detected_language_code = proto.Field(proto.STRING, number=4,) glossary_config = proto.Field( proto.MESSAGE, number=3, message="TranslateTextGlossaryConfig", ) @@ -233,7 +215,6 @@ class Translation(proto.Message): class DetectLanguageRequest(proto.Message): r"""The request message for language detection. - Attributes: parent (str): Required. Project or location to make a call. Must refer to @@ -280,20 +261,15 @@ class DetectLanguageRequest(proto.Message): for more information. """ - parent = proto.Field(proto.STRING, number=5) - - model = proto.Field(proto.STRING, number=4) - - content = proto.Field(proto.STRING, number=1, oneof="source") - - mime_type = proto.Field(proto.STRING, number=3) - - labels = proto.MapField(proto.STRING, proto.STRING, number=6) + parent = proto.Field(proto.STRING, number=5,) + model = proto.Field(proto.STRING, number=4,) + content = proto.Field(proto.STRING, number=1, oneof="source",) + mime_type = proto.Field(proto.STRING, number=3,) + labels = proto.MapField(proto.STRING, proto.STRING, number=6,) class DetectedLanguage(proto.Message): r"""The response message for language detection. - Attributes: language_code (str): The BCP-47 language code of source content in @@ -303,14 +279,12 @@ class DetectedLanguage(proto.Message): this language. """ - language_code = proto.Field(proto.STRING, number=1) - - confidence = proto.Field(proto.FLOAT, number=2) + language_code = proto.Field(proto.STRING, number=1,) + confidence = proto.Field(proto.FLOAT, number=2,) class DetectLanguageResponse(proto.Message): r"""The response message for language detection. - Attributes: languages (Sequence[google.cloud.translate_v3.types.DetectedLanguage]): A list of detected languages sorted by @@ -325,7 +299,6 @@ class DetectLanguageResponse(proto.Message): class GetSupportedLanguagesRequest(proto.Message): r"""The request message for discovering supported languages. - Attributes: parent (str): Required. Project or location to make a call. Must refer to @@ -365,16 +338,13 @@ class GetSupportedLanguagesRequest(proto.Message): (PBMT) model. """ - parent = proto.Field(proto.STRING, number=3) - - display_language_code = proto.Field(proto.STRING, number=1) - - model = proto.Field(proto.STRING, number=2) + parent = proto.Field(proto.STRING, number=3,) + display_language_code = proto.Field(proto.STRING, number=1,) + model = proto.Field(proto.STRING, number=2,) class SupportedLanguages(proto.Message): r"""The response message for discovering supported languages. - Attributes: languages (Sequence[google.cloud.translate_v3.types.SupportedLanguage]): A list of supported language responses. This @@ -408,30 +378,25 @@ class SupportedLanguage(proto.Message): Can be used as target language. """ - language_code = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - support_source = proto.Field(proto.BOOL, number=3) - - support_target = proto.Field(proto.BOOL, number=4) + language_code = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + support_source = proto.Field(proto.BOOL, number=3,) + support_target = proto.Field(proto.BOOL, number=4,) class GcsSource(proto.Message): r"""The Google Cloud Storage location for the input content. - Attributes: input_uri (str): Required. Source data URI. For example, ``gs://my_bucket/my_object``. """ - input_uri = proto.Field(proto.STRING, number=1) + input_uri = proto.Field(proto.STRING, number=1,) class InputConfig(proto.Message): r"""Input configuration for BatchTranslateText request. - Attributes: mime_type (str): Optional. Can be "text/plain" or "text/html". For ``.tsv``, @@ -460,8 +425,7 @@ class InputConfig(proto.Message): ``.html``, which is treated as a single large chunk of text. """ - mime_type = proto.Field(proto.STRING, number=1) - + mime_type = proto.Field(proto.STRING, number=1,) gcs_source = proto.Field( proto.MESSAGE, number=2, oneof="source", message="GcsSource", ) @@ -469,7 +433,6 @@ class InputConfig(proto.Message): class GcsDestination(proto.Message): r"""The Google Cloud Storage location for the output content. - Attributes: output_uri_prefix (str): Required. There must be no files under 'output_uri_prefix'. @@ -478,12 +441,11 @@ class GcsDestination(proto.Message): returned. """ - output_uri_prefix = proto.Field(proto.STRING, number=1) + output_uri_prefix = proto.Field(proto.STRING, number=1,) class OutputConfig(proto.Message): r"""Output configuration for BatchTranslateText request. - Attributes: gcs_destination (google.cloud.translate_v3.types.GcsDestination): Google Cloud Storage destination for output content. For @@ -566,7 +528,6 @@ class OutputConfig(proto.Message): class BatchTranslateTextRequest(proto.Message): r"""The batch translation request. - Attributes: parent (str): Required. Location to make a call. Must refer to a caller's @@ -630,28 +591,20 @@ class BatchTranslateTextRequest(proto.Message): for more information. """ - parent = proto.Field(proto.STRING, number=1) - - source_language_code = proto.Field(proto.STRING, number=2) - - target_language_codes = proto.RepeatedField(proto.STRING, number=3) - - models = proto.MapField(proto.STRING, proto.STRING, number=4) - + parent = proto.Field(proto.STRING, number=1,) + source_language_code = proto.Field(proto.STRING, number=2,) + target_language_codes = proto.RepeatedField(proto.STRING, number=3,) + models = proto.MapField(proto.STRING, proto.STRING, number=4,) input_configs = proto.RepeatedField(proto.MESSAGE, number=5, message="InputConfig",) - output_config = proto.Field(proto.MESSAGE, number=6, message="OutputConfig",) - glossaries = proto.MapField( proto.STRING, proto.MESSAGE, number=7, message="TranslateTextGlossaryConfig", ) - - labels = proto.MapField(proto.STRING, proto.STRING, number=9) + labels = proto.MapField(proto.STRING, proto.STRING, number=9,) class BatchTranslateMetadata(proto.Message): r"""State metadata for the batch translation operation. - Attributes: state (google.cloud.translate_v3.types.BatchTranslateMetadata.State): The state of the operation. @@ -681,14 +634,10 @@ class State(proto.Enum): CANCELLED = 5 state = proto.Field(proto.ENUM, number=1, enum=State,) - - translated_characters = proto.Field(proto.INT64, number=2) - - failed_characters = proto.Field(proto.INT64, number=3) - - total_characters = proto.Field(proto.INT64, number=4) - - submit_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + translated_characters = proto.Field(proto.INT64, number=2,) + failed_characters = proto.Field(proto.INT64, number=3,) + total_characters = proto.Field(proto.INT64, number=4,) + submit_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) class BatchTranslateResponse(proto.Message): @@ -715,20 +664,15 @@ class BatchTranslateResponse(proto.Message): is set to true. """ - total_characters = proto.Field(proto.INT64, number=1) - - translated_characters = proto.Field(proto.INT64, number=2) - - failed_characters = proto.Field(proto.INT64, number=3) - - submit_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + total_characters = proto.Field(proto.INT64, number=1,) + translated_characters = proto.Field(proto.INT64, number=2,) + failed_characters = proto.Field(proto.INT64, number=3,) + submit_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) class GlossaryInputConfig(proto.Message): r"""Input configuration for glossaries. - Attributes: gcs_source (google.cloud.translate_v3.types.GcsSource): Required. Google Cloud Storage location of glossary data. @@ -765,7 +709,6 @@ class GlossaryInputConfig(proto.Message): class Glossary(proto.Message): r"""Represents a glossary built from user provided data. - Attributes: name (str): Required. The resource name of the glossary. Glossary names @@ -791,7 +734,6 @@ class Glossary(proto.Message): class LanguageCodePair(proto.Message): r"""Used with unidirectional glossaries. - Attributes: source_language_code (str): Required. The BCP-47 language code of the input text, for @@ -803,13 +745,11 @@ class LanguageCodePair(proto.Message): GlossaryTerm.language_code. """ - source_language_code = proto.Field(proto.STRING, number=1) - - target_language_code = proto.Field(proto.STRING, number=2) + source_language_code = proto.Field(proto.STRING, number=1,) + target_language_code = proto.Field(proto.STRING, number=2,) class LanguageCodesSet(proto.Message): r"""Used with equivalent term set glossaries. - Attributes: language_codes (Sequence[str]): The BCP-47 language code(s) for terms defined in the @@ -818,30 +758,23 @@ class LanguageCodesSet(proto.Message): GlossaryTerm.language_code. """ - language_codes = proto.RepeatedField(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=1) + language_codes = proto.RepeatedField(proto.STRING, number=1,) + name = proto.Field(proto.STRING, number=1,) language_pair = proto.Field( proto.MESSAGE, number=3, oneof="languages", message=LanguageCodePair, ) - language_codes_set = proto.Field( proto.MESSAGE, number=4, oneof="languages", message=LanguageCodesSet, ) - input_config = proto.Field(proto.MESSAGE, number=5, message="GlossaryInputConfig",) - - entry_count = proto.Field(proto.INT32, number=6) - - submit_time = proto.Field(proto.MESSAGE, number=7, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=8, message=timestamp.Timestamp,) + entry_count = proto.Field(proto.INT32, number=6,) + submit_time = proto.Field(proto.MESSAGE, number=7, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=8, message=timestamp_pb2.Timestamp,) class CreateGlossaryRequest(proto.Message): r"""Request message for CreateGlossary. - Attributes: parent (str): Required. The project name. @@ -849,37 +782,33 @@ class CreateGlossaryRequest(proto.Message): Required. The glossary to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) glossary = proto.Field(proto.MESSAGE, number=2, message="Glossary",) class GetGlossaryRequest(proto.Message): r"""Request message for GetGlossary. - Attributes: name (str): Required. The name of the glossary to retrieve. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class DeleteGlossaryRequest(proto.Message): r"""Request message for DeleteGlossary. - Attributes: name (str): Required. The name of the glossary to delete. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListGlossariesRequest(proto.Message): r"""Request message for ListGlossaries. - Attributes: parent (str): Required. The name of the project from which @@ -902,18 +831,14 @@ class ListGlossariesRequest(proto.Message): missing, no filtering is performed. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - filter = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + filter = proto.Field(proto.STRING, number=4,) class ListGlossariesResponse(proto.Message): r"""Response message for ListGlossaries. - Attributes: glossaries (Sequence[google.cloud.translate_v3.types.Glossary]): The list of glossaries for a project. @@ -929,8 +854,7 @@ def raw_page(self): return self glossaries = proto.RepeatedField(proto.MESSAGE, number=1, message="Glossary",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class CreateGlossaryMetadata(proto.Message): @@ -961,11 +885,9 @@ class State(proto.Enum): CANCELLING = 4 CANCELLED = 5 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) state = proto.Field(proto.ENUM, number=2, enum=State,) - - submit_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + submit_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) class DeleteGlossaryMetadata(proto.Message): @@ -996,11 +918,9 @@ class State(proto.Enum): CANCELLING = 4 CANCELLED = 5 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) state = proto.Field(proto.ENUM, number=2, enum=State,) - - submit_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + submit_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) class DeleteGlossaryResponse(proto.Message): @@ -1020,11 +940,9 @@ class DeleteGlossaryResponse(proto.Message): is set to true. """ - name = proto.Field(proto.STRING, number=1) - - submit_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + name = proto.Field(proto.STRING, number=1,) + submit_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/translate_v3beta1/__init__.py b/google/cloud/translate_v3beta1/__init__.py index 80a31e78..0bd85463 100644 --- a/google/cloud/translate_v3beta1/__init__.py +++ b/google/cloud/translate_v3beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,6 +15,8 @@ # from .services.translation_service import TranslationServiceClient +from .services.translation_service import TranslationServiceAsyncClient + from .types.translation_service import BatchDocumentInputConfig from .types.translation_service import BatchDocumentOutputConfig from .types.translation_service import BatchTranslateDocumentMetadata @@ -29,9 +30,9 @@ from .types.translation_service import DeleteGlossaryMetadata from .types.translation_service import DeleteGlossaryRequest from .types.translation_service import DeleteGlossaryResponse +from .types.translation_service import DetectedLanguage from .types.translation_service import DetectLanguageRequest from .types.translation_service import DetectLanguageResponse -from .types.translation_service import DetectedLanguage from .types.translation_service import DocumentInputConfig from .types.translation_service import DocumentOutputConfig from .types.translation_service import DocumentTranslation @@ -54,8 +55,8 @@ from .types.translation_service import TranslateTextResponse from .types.translation_service import Translation - __all__ = ( + "TranslationServiceAsyncClient", "BatchDocumentInputConfig", "BatchDocumentOutputConfig", "BatchTranslateDocumentMetadata", diff --git a/google/cloud/translate_v3beta1/gapic_metadata.json b/google/cloud/translate_v3beta1/gapic_metadata.json new file mode 100644 index 00000000..f3ed7241 --- /dev/null +++ b/google/cloud/translate_v3beta1/gapic_metadata.json @@ -0,0 +1,123 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.translate_v3beta1", + "protoPackage": "google.cloud.translation.v3beta1", + "schema": "1.0", + "services": { + "TranslationService": { + "clients": { + "grpc": { + "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" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TranslationServiceAsyncClient", + "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/__init__.py b/google/cloud/translate_v3beta1/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/translate_v3beta1/services/__init__.py +++ b/google/cloud/translate_v3beta1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/translate_v3beta1/services/translation_service/__init__.py b/google/cloud/translate_v3beta1/services/translation_service/__init__.py index e2442711..6d42bf0e 100644 --- a/google/cloud/translate_v3beta1/services/translation_service/__init__.py +++ b/google/cloud/translate_v3beta1/services/translation_service/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import TranslationServiceClient from .async_client import TranslationServiceAsyncClient diff --git a/google/cloud/translate_v3beta1/services/translation_service/async_client.py b/google/cloud/translate_v3beta1/services/translation_service/async_client.py index f4b201cf..c508b9d0 100644 --- a/google/cloud/translate_v3beta1/services/translation_service/async_client.py +++ b/google/cloud/translate_v3beta1/services/translation_service/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,18 +20,17 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.translate_v3beta1.services.translation_service import pagers from google.cloud.translate_v3beta1.types import translation_service -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import TranslationServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import TranslationServiceGrpcAsyncIOTransport from .client import TranslationServiceClient @@ -49,31 +46,26 @@ class TranslationServiceAsyncClient: glossary_path = staticmethod(TranslationServiceClient.glossary_path) parse_glossary_path = staticmethod(TranslationServiceClient.parse_glossary_path) - common_billing_account_path = staticmethod( TranslationServiceClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( TranslationServiceClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(TranslationServiceClient.common_folder_path) parse_common_folder_path = staticmethod( TranslationServiceClient.parse_common_folder_path ) - common_organization_path = staticmethod( TranslationServiceClient.common_organization_path ) parse_common_organization_path = staticmethod( TranslationServiceClient.parse_common_organization_path ) - common_project_path = staticmethod(TranslationServiceClient.common_project_path) parse_common_project_path = staticmethod( TranslationServiceClient.parse_common_project_path ) - common_location_path = staticmethod(TranslationServiceClient.common_location_path) parse_common_location_path = staticmethod( TranslationServiceClient.parse_common_location_path @@ -81,7 +73,8 @@ class TranslationServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -96,7 +89,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -113,7 +106,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TranslationServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: TranslationServiceTransport: The transport used by the client instance. @@ -128,12 +121,12 @@ def transport(self) -> TranslationServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, TranslationServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the translation service client. + """Instantiates the translation service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -165,7 +158,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = TranslationServiceClient( credentials=credentials, transport=transport, @@ -187,7 +179,6 @@ async def translate_text( request (:class:`google.cloud.translate_v3beta1.types.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. @@ -199,7 +190,6 @@ async def translate_text( """ # Create or coerce a protobuf request object. - request = translation_service.TranslateTextRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -282,7 +272,6 @@ async def detect_language( This corresponds to the ``mime_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -309,7 +298,6 @@ async def detect_language( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if model is not None: @@ -404,7 +392,6 @@ async def get_supported_languages( This corresponds to the ``model`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -431,7 +418,6 @@ async def get_supported_languages( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if display_language_code is not None: @@ -448,7 +434,8 @@ async def get_supported_languages( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -481,7 +468,6 @@ async def translate_document( Args: request (:class:`google.cloud.translate_v3beta1.types.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. @@ -495,7 +481,6 @@ async def translate_document( """ # Create or coerce a protobuf request object. - request = translation_service.TranslateDocumentRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -539,7 +524,6 @@ async def batch_translate_text( Args: request (:class:`google.cloud.translate_v3beta1.types.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. @@ -557,7 +541,6 @@ async def batch_translate_text( """ # Create or coerce a protobuf request object. - request = translation_service.BatchTranslateTextRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -609,7 +592,6 @@ async def batch_translate_document( Args: request (:class:`google.cloud.translate_v3beta1.types.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. @@ -627,7 +609,6 @@ async def batch_translate_document( """ # Create or coerce a protobuf request object. - request = translation_service.BatchTranslateDocumentRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -684,7 +665,6 @@ async def create_glossary( This corresponds to the ``glossary`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -714,7 +694,6 @@ async def create_glossary( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if glossary is not None: @@ -806,7 +785,6 @@ async def list_glossaries( This corresponds to the ``filter`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -835,7 +813,6 @@ async def list_glossaries( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if filter is not None: @@ -850,7 +827,8 @@ async def list_glossaries( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -898,7 +876,6 @@ async def get_glossary( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -925,7 +902,6 @@ async def get_glossary( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -938,7 +914,8 @@ async def get_glossary( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -981,7 +958,6 @@ async def delete_glossary( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1011,7 +987,6 @@ async def delete_glossary( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1024,7 +999,8 @@ async def delete_glossary( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), diff --git a/google/cloud/translate_v3beta1/services/translation_service/client.py b/google/cloud/translate_v3beta1/services/translation_service/client.py index f2623a3b..bef32c45 100644 --- a/google/cloud/translate_v3beta1/services/translation_service/client.py +++ b/google/cloud/translate_v3beta1/services/translation_service/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -36,8 +34,7 @@ from google.api_core import operation_async # type: ignore from google.cloud.translate_v3beta1.services.translation_service import pagers from google.cloud.translate_v3beta1.types import translation_service -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import TranslationServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import TranslationServiceGrpcTransport from .transports.grpc_asyncio import TranslationServiceGrpcAsyncIOTransport @@ -60,7 +57,7 @@ class TranslationServiceClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[TranslationServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -83,7 +80,8 @@ class TranslationServiceClient(metaclass=TranslationServiceClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -117,7 +115,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -134,7 +133,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -153,23 +152,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TranslationServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - TranslationServiceTransport: The transport used by the client instance. + TranslationServiceTransport: The transport used by the client + instance. """ return self._transport @staticmethod def glossary_path(project: str, location: str, glossary: str,) -> str: - """Return a fully-qualified glossary string.""" + """Returns a fully-qualified glossary string.""" return "projects/{project}/locations/{location}/glossaries/{glossary}".format( project=project, location=location, glossary=glossary, ) @staticmethod def parse_glossary_path(path: str) -> Dict[str, str]: - """Parse a glossary path into its component segments.""" + """Parses a glossary path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/glossaries/(?P.+?)$", path, @@ -178,7 +178,7 @@ def parse_glossary_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -191,7 +191,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -202,7 +202,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -213,7 +213,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -224,7 +224,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -238,12 +238,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, TranslationServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the translation service client. + """Instantiates the translation service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -298,9 +298,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -312,12 +313,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -332,8 +335,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -362,7 +365,6 @@ def translate_text( request (google.cloud.translate_v3beta1.types.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. @@ -374,7 +376,6 @@ def translate_text( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a translation_service.TranslateTextRequest. # There's no risk of modifying the input as we've already verified @@ -458,7 +459,6 @@ def detect_language( This corresponds to the ``mime_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -487,10 +487,8 @@ def detect_language( # there are no flattened fields. if not isinstance(request, translation_service.DetectLanguageRequest): request = translation_service.DetectLanguageRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if model is not None: @@ -581,7 +579,6 @@ def get_supported_languages( This corresponds to the ``model`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -610,10 +607,8 @@ def get_supported_languages( # there are no flattened fields. if not isinstance(request, translation_service.GetSupportedLanguagesRequest): request = translation_service.GetSupportedLanguagesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if display_language_code is not None: @@ -650,7 +645,6 @@ def translate_document( Args: request (google.cloud.translate_v3beta1.types.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. @@ -664,7 +658,6 @@ def translate_document( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a translation_service.TranslateDocumentRequest. # There's no risk of modifying the input as we've already verified @@ -709,7 +702,6 @@ def batch_translate_text( Args: request (google.cloud.translate_v3beta1.types.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. @@ -727,7 +719,6 @@ def batch_translate_text( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a translation_service.BatchTranslateTextRequest. # There's no risk of modifying the input as we've already verified @@ -780,7 +771,6 @@ def batch_translate_document( Args: request (google.cloud.translate_v3beta1.types.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. @@ -798,7 +788,6 @@ def batch_translate_document( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a translation_service.BatchTranslateDocumentRequest. # There's no risk of modifying the input as we've already verified @@ -856,7 +845,6 @@ def create_glossary( This corresponds to the ``glossary`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -888,10 +876,8 @@ def create_glossary( # there are no flattened fields. if not isinstance(request, translation_service.CreateGlossaryRequest): request = translation_service.CreateGlossaryRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if glossary is not None: @@ -979,7 +965,6 @@ def list_glossaries( This corresponds to the ``filter`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1010,10 +995,8 @@ def list_glossaries( # there are no flattened fields. if not isinstance(request, translation_service.ListGlossariesRequest): request = translation_service.ListGlossariesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if filter is not None: @@ -1063,7 +1046,6 @@ def get_glossary( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1092,10 +1074,8 @@ def get_glossary( # there are no flattened fields. if not isinstance(request, translation_service.GetGlossaryRequest): request = translation_service.GetGlossaryRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1138,7 +1118,6 @@ def delete_glossary( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1170,10 +1149,8 @@ def delete_glossary( # there are no flattened fields. if not isinstance(request, translation_service.DeleteGlossaryRequest): request = translation_service.DeleteGlossaryRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/translate_v3beta1/services/translation_service/pagers.py b/google/cloud/translate_v3beta1/services/translation_service/pagers.py index a750c43d..b1a0f8f9 100644 --- a/google/cloud/translate_v3beta1/services/translation_service/pagers.py +++ b/google/cloud/translate_v3beta1/services/translation_service/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and 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 92859637..11cb0a7d 100644 --- a/google/cloud/translate_v3beta1/services/translation_service/transports/__init__.py +++ b/google/cloud/translate_v3beta1/services/translation_service/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/translate_v3beta1/services/translation_service/transports/base.py b/google/cloud/translate_v3beta1/services/translation_service/transports/base.py index c8a24ade..b951738b 100644 --- a/google/cloud/translate_v3beta1/services/translation_service/transports/base.py +++ b/google/cloud/translate_v3beta1/services/translation_service/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.translate_v3beta1.types import translation_service -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -37,6 +36,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class TranslationServiceTransport(abc.ABC): """Abstract transport class for TranslationService.""" @@ -46,21 +56,24 @@ class TranslationServiceTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-translation", ) + DEFAULT_HOST: str = "translate.googleapis.com" + def __init__( self, *, - host: str = "translate.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -69,7 +82,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -83,29 +96,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -122,7 +182,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -152,7 +213,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -166,7 +228,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -180,7 +243,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -197,11 +261,11 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def translate_text( self, - ) -> typing.Callable[ + ) -> Callable[ [translation_service.TranslateTextRequest], - typing.Union[ + Union[ translation_service.TranslateTextResponse, - typing.Awaitable[translation_service.TranslateTextResponse], + Awaitable[translation_service.TranslateTextResponse], ], ]: raise NotImplementedError() @@ -209,11 +273,11 @@ def translate_text( @property def detect_language( self, - ) -> typing.Callable[ + ) -> Callable[ [translation_service.DetectLanguageRequest], - typing.Union[ + Union[ translation_service.DetectLanguageResponse, - typing.Awaitable[translation_service.DetectLanguageResponse], + Awaitable[translation_service.DetectLanguageResponse], ], ]: raise NotImplementedError() @@ -221,11 +285,11 @@ def detect_language( @property def get_supported_languages( self, - ) -> typing.Callable[ + ) -> Callable[ [translation_service.GetSupportedLanguagesRequest], - typing.Union[ + Union[ translation_service.SupportedLanguages, - typing.Awaitable[translation_service.SupportedLanguages], + Awaitable[translation_service.SupportedLanguages], ], ]: raise NotImplementedError() @@ -233,11 +297,11 @@ def get_supported_languages( @property def translate_document( self, - ) -> typing.Callable[ + ) -> Callable[ [translation_service.TranslateDocumentRequest], - typing.Union[ + Union[ translation_service.TranslateDocumentResponse, - typing.Awaitable[translation_service.TranslateDocumentResponse], + Awaitable[translation_service.TranslateDocumentResponse], ], ]: raise NotImplementedError() @@ -245,38 +309,38 @@ def translate_document( @property def batch_translate_text( self, - ) -> typing.Callable[ + ) -> Callable[ [translation_service.BatchTranslateTextRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_translate_document( self, - ) -> typing.Callable[ + ) -> Callable[ [translation_service.BatchTranslateDocumentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def create_glossary( self, - ) -> typing.Callable[ + ) -> Callable[ [translation_service.CreateGlossaryRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def list_glossaries( self, - ) -> typing.Callable[ + ) -> Callable[ [translation_service.ListGlossariesRequest], - typing.Union[ + Union[ translation_service.ListGlossariesResponse, - typing.Awaitable[translation_service.ListGlossariesResponse], + Awaitable[translation_service.ListGlossariesResponse], ], ]: raise NotImplementedError() @@ -284,20 +348,18 @@ def list_glossaries( @property def get_glossary( self, - ) -> typing.Callable[ + ) -> Callable[ [translation_service.GetGlossaryRequest], - typing.Union[ - translation_service.Glossary, typing.Awaitable[translation_service.Glossary] - ], + Union[translation_service.Glossary, Awaitable[translation_service.Glossary]], ]: raise NotImplementedError() @property def delete_glossary( self, - ) -> typing.Callable[ + ) -> Callable[ [translation_service.DeleteGlossaryRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/translate_v3beta1/services/translation_service/transports/grpc.py b/google/cloud/translate_v3beta1/services/translation_service/transports/grpc.py index 9a903357..72570c18 100644 --- a/google/cloud/translate_v3beta1/services/translation_service/transports/grpc.py +++ b/google/cloud/translate_v3beta1/services/translation_service/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.translate_v3beta1.types import translation_service -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import TranslationServiceTransport, DEFAULT_CLIENT_INFO @@ -52,7 +49,7 @@ def __init__( self, *, host: str = "translate.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -66,7 +63,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -177,7 +175,7 @@ def __init__( def create_channel( cls, host: str = "translate.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -208,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -359,7 +359,7 @@ def translate_document( def batch_translate_text( self, ) -> Callable[ - [translation_service.BatchTranslateTextRequest], operations.Operation + [translation_service.BatchTranslateTextRequest], operations_pb2.Operation ]: r"""Return a callable for the batch translate text method over gRPC. @@ -387,7 +387,7 @@ def batch_translate_text( self._stubs["batch_translate_text"] = self.grpc_channel.unary_unary( "/google.cloud.translation.v3beta1.TranslationService/BatchTranslateText", request_serializer=translation_service.BatchTranslateTextRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_translate_text"] @@ -395,7 +395,7 @@ def batch_translate_text( def batch_translate_document( self, ) -> Callable[ - [translation_service.BatchTranslateDocumentRequest], operations.Operation + [translation_service.BatchTranslateDocumentRequest], operations_pb2.Operation ]: r"""Return a callable for the batch translate document method over gRPC. @@ -423,14 +423,16 @@ def batch_translate_document( self._stubs["batch_translate_document"] = self.grpc_channel.unary_unary( "/google.cloud.translation.v3beta1.TranslationService/BatchTranslateDocument", request_serializer=translation_service.BatchTranslateDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_translate_document"] @property def create_glossary( self, - ) -> Callable[[translation_service.CreateGlossaryRequest], operations.Operation]: + ) -> Callable[ + [translation_service.CreateGlossaryRequest], operations_pb2.Operation + ]: r"""Return a callable for the create glossary method over gRPC. Creates a glossary and returns the long-running operation. @@ -450,7 +452,7 @@ def create_glossary( self._stubs["create_glossary"] = self.grpc_channel.unary_unary( "/google.cloud.translation.v3beta1.TranslationService/CreateGlossary", request_serializer=translation_service.CreateGlossaryRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_glossary"] @@ -516,7 +518,9 @@ def get_glossary( @property def delete_glossary( self, - ) -> Callable[[translation_service.DeleteGlossaryRequest], operations.Operation]: + ) -> Callable[ + [translation_service.DeleteGlossaryRequest], operations_pb2.Operation + ]: r"""Return a callable for the delete glossary method over gRPC. Deletes a glossary, or cancels glossary construction if the @@ -537,7 +541,7 @@ def delete_glossary( self._stubs["delete_glossary"] = self.grpc_channel.unary_unary( "/google.cloud.translation.v3beta1.TranslationService/DeleteGlossary", request_serializer=translation_service.DeleteGlossaryRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_glossary"] diff --git a/google/cloud/translate_v3beta1/services/translation_service/transports/grpc_asyncio.py b/google/cloud/translate_v3beta1/services/translation_service/transports/grpc_asyncio.py index 72617ed7..f1cf85fa 100644 --- a/google/cloud/translate_v3beta1/services/translation_service/transports/grpc_asyncio.py +++ b/google/cloud/translate_v3beta1/services/translation_service/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.translate_v3beta1.types import translation_service -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import TranslationServiceTransport, DEFAULT_CLIENT_INFO from .grpc import TranslationServiceGrpcTransport @@ -55,7 +52,7 @@ class TranslationServiceGrpcAsyncIOTransport(TranslationServiceTransport): def create_channel( cls, host: str = "translate.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -82,13 +79,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -96,7 +95,7 @@ def __init__( self, *, host: str = "translate.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -110,7 +109,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -169,7 +169,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -365,7 +364,8 @@ def translate_document( def batch_translate_text( self, ) -> Callable[ - [translation_service.BatchTranslateTextRequest], Awaitable[operations.Operation] + [translation_service.BatchTranslateTextRequest], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the batch translate text method over gRPC. @@ -393,7 +393,7 @@ def batch_translate_text( self._stubs["batch_translate_text"] = self.grpc_channel.unary_unary( "/google.cloud.translation.v3beta1.TranslationService/BatchTranslateText", request_serializer=translation_service.BatchTranslateTextRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_translate_text"] @@ -402,7 +402,7 @@ def batch_translate_document( self, ) -> Callable[ [translation_service.BatchTranslateDocumentRequest], - Awaitable[operations.Operation], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the batch translate document method over gRPC. @@ -430,7 +430,7 @@ def batch_translate_document( self._stubs["batch_translate_document"] = self.grpc_channel.unary_unary( "/google.cloud.translation.v3beta1.TranslationService/BatchTranslateDocument", request_serializer=translation_service.BatchTranslateDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_translate_document"] @@ -438,7 +438,7 @@ def batch_translate_document( def create_glossary( self, ) -> Callable[ - [translation_service.CreateGlossaryRequest], Awaitable[operations.Operation] + [translation_service.CreateGlossaryRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the create glossary method over gRPC. @@ -459,7 +459,7 @@ def create_glossary( self._stubs["create_glossary"] = self.grpc_channel.unary_unary( "/google.cloud.translation.v3beta1.TranslationService/CreateGlossary", request_serializer=translation_service.CreateGlossaryRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_glossary"] @@ -527,7 +527,7 @@ def get_glossary( def delete_glossary( self, ) -> Callable[ - [translation_service.DeleteGlossaryRequest], Awaitable[operations.Operation] + [translation_service.DeleteGlossaryRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the delete glossary method over gRPC. @@ -549,7 +549,7 @@ def delete_glossary( self._stubs["delete_glossary"] = self.grpc_channel.unary_unary( "/google.cloud.translation.v3beta1.TranslationService/DeleteGlossary", request_serializer=translation_service.DeleteGlossaryRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_glossary"] diff --git a/google/cloud/translate_v3beta1/types/__init__.py b/google/cloud/translate_v3beta1/types/__init__.py index 64ad8390..38820580 100644 --- a/google/cloud/translate_v3beta1/types/__init__.py +++ b/google/cloud/translate_v3beta1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .translation_service import ( BatchDocumentInputConfig, BatchDocumentOutputConfig, diff --git a/google/cloud/translate_v3beta1/types/translation_service.py b/google/cloud/translate_v3beta1/types/translation_service.py index 3398dc13..665bccee 100644 --- a/google/cloud/translate_v3beta1/types/translation_service.py +++ b/google/cloud/translate_v3beta1/types/translation_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -78,14 +75,12 @@ class TranslateTextGlossaryConfig(proto.Message): nsensitive. Default value is false if missing. """ - glossary = proto.Field(proto.STRING, number=1) - - ignore_case = proto.Field(proto.BOOL, number=2) + glossary = proto.Field(proto.STRING, number=1,) + ignore_case = proto.Field(proto.BOOL, number=2,) class TranslateTextRequest(proto.Message): r"""The request message for synchronous translation. - Attributes: contents (Sequence[str]): Required. The content of the input in string @@ -163,28 +158,20 @@ class TranslateTextRequest(proto.Message): for more information. """ - contents = proto.RepeatedField(proto.STRING, number=1) - - mime_type = proto.Field(proto.STRING, number=3) - - source_language_code = proto.Field(proto.STRING, number=4) - - target_language_code = proto.Field(proto.STRING, number=5) - - parent = proto.Field(proto.STRING, number=8) - - model = proto.Field(proto.STRING, number=6) - + contents = proto.RepeatedField(proto.STRING, number=1,) + mime_type = proto.Field(proto.STRING, number=3,) + source_language_code = proto.Field(proto.STRING, number=4,) + target_language_code = proto.Field(proto.STRING, number=5,) + parent = proto.Field(proto.STRING, number=8,) + model = proto.Field(proto.STRING, number=6,) glossary_config = proto.Field( proto.MESSAGE, number=7, message="TranslateTextGlossaryConfig", ) - - labels = proto.MapField(proto.STRING, proto.STRING, number=10) + labels = proto.MapField(proto.STRING, proto.STRING, number=10,) class TranslateTextResponse(proto.Message): r""" - Attributes: translations (Sequence[google.cloud.translate_v3beta1.types.Translation]): Text translation responses with no glossary applied. This @@ -199,7 +186,6 @@ class TranslateTextResponse(proto.Message): """ translations = proto.RepeatedField(proto.MESSAGE, number=1, message="Translation",) - glossary_translations = proto.RepeatedField( proto.MESSAGE, number=3, message="Translation", ) @@ -207,7 +193,6 @@ class TranslateTextResponse(proto.Message): class Translation(proto.Message): r"""A single translation response. - Attributes: translated_text (str): Text translated into the target language. @@ -231,12 +216,9 @@ class Translation(proto.Message): The ``glossary_config`` used for this translation. """ - translated_text = proto.Field(proto.STRING, number=1) - - model = proto.Field(proto.STRING, number=2) - - detected_language_code = proto.Field(proto.STRING, number=4) - + translated_text = proto.Field(proto.STRING, number=1,) + model = proto.Field(proto.STRING, number=2,) + detected_language_code = proto.Field(proto.STRING, number=4,) glossary_config = proto.Field( proto.MESSAGE, number=3, message="TranslateTextGlossaryConfig", ) @@ -244,7 +226,6 @@ class Translation(proto.Message): class DetectLanguageRequest(proto.Message): r"""The request message for language detection. - Attributes: parent (str): Required. Project or location to make a call. Must refer to @@ -291,20 +272,15 @@ class DetectLanguageRequest(proto.Message): for more information. """ - parent = proto.Field(proto.STRING, number=5) - - model = proto.Field(proto.STRING, number=4) - - content = proto.Field(proto.STRING, number=1, oneof="source") - - mime_type = proto.Field(proto.STRING, number=3) - - labels = proto.MapField(proto.STRING, proto.STRING, number=6) + parent = proto.Field(proto.STRING, number=5,) + model = proto.Field(proto.STRING, number=4,) + content = proto.Field(proto.STRING, number=1, oneof="source",) + mime_type = proto.Field(proto.STRING, number=3,) + labels = proto.MapField(proto.STRING, proto.STRING, number=6,) class DetectedLanguage(proto.Message): r"""The response message for language detection. - Attributes: language_code (str): The BCP-47 language code of source content in @@ -314,14 +290,12 @@ class DetectedLanguage(proto.Message): this language. """ - language_code = proto.Field(proto.STRING, number=1) - - confidence = proto.Field(proto.FLOAT, number=2) + language_code = proto.Field(proto.STRING, number=1,) + confidence = proto.Field(proto.FLOAT, number=2,) class DetectLanguageResponse(proto.Message): r"""The response message for language detection. - Attributes: languages (Sequence[google.cloud.translate_v3beta1.types.DetectedLanguage]): A list of detected languages sorted by @@ -336,7 +310,6 @@ class DetectLanguageResponse(proto.Message): class GetSupportedLanguagesRequest(proto.Message): r"""The request message for discovering supported languages. - Attributes: parent (str): Required. Project or location to make a call. Must refer to @@ -376,16 +349,13 @@ class GetSupportedLanguagesRequest(proto.Message): (PBMT) model. """ - parent = proto.Field(proto.STRING, number=3) - - display_language_code = proto.Field(proto.STRING, number=1) - - model = proto.Field(proto.STRING, number=2) + parent = proto.Field(proto.STRING, number=3,) + display_language_code = proto.Field(proto.STRING, number=1,) + model = proto.Field(proto.STRING, number=2,) class SupportedLanguages(proto.Message): r"""The response message for discovering supported languages. - Attributes: languages (Sequence[google.cloud.translate_v3beta1.types.SupportedLanguage]): A list of supported language responses. This @@ -419,30 +389,25 @@ class SupportedLanguage(proto.Message): Can be used as target language. """ - language_code = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - support_source = proto.Field(proto.BOOL, number=3) - - support_target = proto.Field(proto.BOOL, number=4) + language_code = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + support_source = proto.Field(proto.BOOL, number=3,) + support_target = proto.Field(proto.BOOL, number=4,) class GcsSource(proto.Message): r"""The Google Cloud Storage location for the input content. - Attributes: input_uri (str): Required. Source data URI. For example, ``gs://my_bucket/my_object``. """ - input_uri = proto.Field(proto.STRING, number=1) + input_uri = proto.Field(proto.STRING, number=1,) class InputConfig(proto.Message): r"""Input configuration for BatchTranslateText request. - Attributes: mime_type (str): Optional. Can be "text/plain" or "text/html". For ``.tsv``, @@ -471,8 +436,7 @@ class InputConfig(proto.Message): ``.html``, which is treated as a single large chunk of text. """ - mime_type = proto.Field(proto.STRING, number=1) - + mime_type = proto.Field(proto.STRING, number=1,) gcs_source = proto.Field( proto.MESSAGE, number=2, oneof="source", message="GcsSource", ) @@ -480,7 +444,6 @@ class InputConfig(proto.Message): class GcsDestination(proto.Message): r"""The Google Cloud Storage location for the output content. - Attributes: output_uri_prefix (str): Required. There must be no files under 'output_uri_prefix'. @@ -489,12 +452,11 @@ class GcsDestination(proto.Message): returned. """ - output_uri_prefix = proto.Field(proto.STRING, number=1) + output_uri_prefix = proto.Field(proto.STRING, number=1,) class OutputConfig(proto.Message): r"""Output configuration for BatchTranslateText request. - Attributes: gcs_destination (google.cloud.translate_v3beta1.types.GcsDestination): Google Cloud Storage destination for output content. For @@ -582,7 +544,6 @@ class OutputConfig(proto.Message): class DocumentInputConfig(proto.Message): r"""A document translation request input config. - Attributes: content (bytes): Document's content represented as a stream of @@ -604,18 +565,15 @@ class DocumentInputConfig(proto.Message): - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet """ - content = proto.Field(proto.BYTES, number=1, oneof="source") - + content = proto.Field(proto.BYTES, number=1, oneof="source",) gcs_source = proto.Field( proto.MESSAGE, number=2, oneof="source", message="GcsSource", ) - - mime_type = proto.Field(proto.STRING, number=4) + mime_type = proto.Field(proto.STRING, number=4,) class DocumentOutputConfig(proto.Message): r"""A document translation request output config. - Attributes: gcs_destination (google.cloud.translate_v3beta1.types.GcsDestination): Optional. Google Cloud Storage destination for the @@ -682,13 +640,11 @@ class DocumentOutputConfig(proto.Message): gcs_destination = proto.Field( proto.MESSAGE, number=1, oneof="destination", message="GcsDestination", ) - - mime_type = proto.Field(proto.STRING, number=3) + mime_type = proto.Field(proto.STRING, number=3,) class TranslateDocumentRequest(proto.Message): r"""A document translation request. - Attributes: parent (str): Required. Location to make a regional call. @@ -763,32 +719,24 @@ class TranslateDocumentRequest(proto.Message): for more information. """ - parent = proto.Field(proto.STRING, number=1) - - source_language_code = proto.Field(proto.STRING, number=2) - - target_language_code = proto.Field(proto.STRING, number=3) - + parent = proto.Field(proto.STRING, number=1,) + source_language_code = proto.Field(proto.STRING, number=2,) + target_language_code = proto.Field(proto.STRING, number=3,) document_input_config = proto.Field( proto.MESSAGE, number=4, message="DocumentInputConfig", ) - document_output_config = proto.Field( proto.MESSAGE, number=5, message="DocumentOutputConfig", ) - - model = proto.Field(proto.STRING, number=6) - + model = proto.Field(proto.STRING, number=6,) glossary_config = proto.Field( proto.MESSAGE, number=7, message="TranslateTextGlossaryConfig", ) - - labels = proto.MapField(proto.STRING, proto.STRING, number=8) + labels = proto.MapField(proto.STRING, proto.STRING, number=8,) class DocumentTranslation(proto.Message): r"""A translated document message. - Attributes: byte_stream_outputs (Sequence[bytes]): The array of translated documents. It is @@ -807,16 +755,13 @@ class DocumentTranslation(proto.Message): empty. """ - byte_stream_outputs = proto.RepeatedField(proto.BYTES, number=1) - - mime_type = proto.Field(proto.STRING, number=2) - - detected_language_code = proto.Field(proto.STRING, number=3) + byte_stream_outputs = proto.RepeatedField(proto.BYTES, number=1,) + mime_type = proto.Field(proto.STRING, number=2,) + detected_language_code = proto.Field(proto.STRING, number=3,) class TranslateDocumentResponse(proto.Message): r"""A translated document response message. - Attributes: document_translation (google.cloud.translate_v3beta1.types.DocumentTranslation): Translated document. @@ -841,13 +786,10 @@ class TranslateDocumentResponse(proto.Message): document_translation = proto.Field( proto.MESSAGE, number=1, message="DocumentTranslation", ) - glossary_document_translation = proto.Field( proto.MESSAGE, number=2, message="DocumentTranslation", ) - - model = proto.Field(proto.STRING, number=3) - + model = proto.Field(proto.STRING, number=3,) glossary_config = proto.Field( proto.MESSAGE, number=4, message="TranslateTextGlossaryConfig", ) @@ -855,7 +797,6 @@ class TranslateDocumentResponse(proto.Message): class BatchTranslateTextRequest(proto.Message): r"""The batch translation request. - Attributes: parent (str): Required. Location to make a call. Must refer to a caller's @@ -920,28 +861,20 @@ class BatchTranslateTextRequest(proto.Message): for more information. """ - parent = proto.Field(proto.STRING, number=1) - - source_language_code = proto.Field(proto.STRING, number=2) - - target_language_codes = proto.RepeatedField(proto.STRING, number=3) - - models = proto.MapField(proto.STRING, proto.STRING, number=4) - + parent = proto.Field(proto.STRING, number=1,) + source_language_code = proto.Field(proto.STRING, number=2,) + target_language_codes = proto.RepeatedField(proto.STRING, number=3,) + models = proto.MapField(proto.STRING, proto.STRING, number=4,) input_configs = proto.RepeatedField(proto.MESSAGE, number=5, message="InputConfig",) - output_config = proto.Field(proto.MESSAGE, number=6, message="OutputConfig",) - glossaries = proto.MapField( proto.STRING, proto.MESSAGE, number=7, message="TranslateTextGlossaryConfig", ) - - labels = proto.MapField(proto.STRING, proto.STRING, number=9) + labels = proto.MapField(proto.STRING, proto.STRING, number=9,) class BatchTranslateMetadata(proto.Message): r"""State metadata for the batch translation operation. - Attributes: state (google.cloud.translate_v3beta1.types.BatchTranslateMetadata.State): The state of the operation. @@ -971,14 +904,10 @@ class State(proto.Enum): CANCELLED = 5 state = proto.Field(proto.ENUM, number=1, enum=State,) - - translated_characters = proto.Field(proto.INT64, number=2) - - failed_characters = proto.Field(proto.INT64, number=3) - - total_characters = proto.Field(proto.INT64, number=4) - - submit_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + translated_characters = proto.Field(proto.INT64, number=2,) + failed_characters = proto.Field(proto.INT64, number=3,) + total_characters = proto.Field(proto.INT64, number=4,) + submit_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) class BatchTranslateResponse(proto.Message): @@ -1005,20 +934,15 @@ class BatchTranslateResponse(proto.Message): is set to true. """ - total_characters = proto.Field(proto.INT64, number=1) - - translated_characters = proto.Field(proto.INT64, number=2) - - failed_characters = proto.Field(proto.INT64, number=3) - - submit_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + total_characters = proto.Field(proto.INT64, number=1,) + translated_characters = proto.Field(proto.INT64, number=2,) + failed_characters = proto.Field(proto.INT64, number=3,) + submit_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) class GlossaryInputConfig(proto.Message): r"""Input configuration for glossaries. - Attributes: gcs_source (google.cloud.translate_v3beta1.types.GcsSource): Required. Google Cloud Storage location of glossary data. @@ -1055,7 +979,6 @@ class GlossaryInputConfig(proto.Message): class Glossary(proto.Message): r"""Represents a glossary built from user provided data. - Attributes: name (str): Required. The resource name of the glossary. Glossary names @@ -1081,7 +1004,6 @@ class Glossary(proto.Message): class LanguageCodePair(proto.Message): r"""Used with unidirectional glossaries. - Attributes: source_language_code (str): Required. The BCP-47 language code of the input text, for @@ -1093,13 +1015,11 @@ class LanguageCodePair(proto.Message): GlossaryTerm.language_code. """ - source_language_code = proto.Field(proto.STRING, number=1) - - target_language_code = proto.Field(proto.STRING, number=2) + source_language_code = proto.Field(proto.STRING, number=1,) + target_language_code = proto.Field(proto.STRING, number=2,) class LanguageCodesSet(proto.Message): r"""Used with equivalent term set glossaries. - Attributes: language_codes (Sequence[str]): The BCP-47 language code(s) for terms defined in the @@ -1108,30 +1028,23 @@ class LanguageCodesSet(proto.Message): GlossaryTerm.language_code. """ - language_codes = proto.RepeatedField(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=1) + language_codes = proto.RepeatedField(proto.STRING, number=1,) + name = proto.Field(proto.STRING, number=1,) language_pair = proto.Field( proto.MESSAGE, number=3, oneof="languages", message=LanguageCodePair, ) - language_codes_set = proto.Field( proto.MESSAGE, number=4, oneof="languages", message=LanguageCodesSet, ) - input_config = proto.Field(proto.MESSAGE, number=5, message="GlossaryInputConfig",) - - entry_count = proto.Field(proto.INT32, number=6) - - submit_time = proto.Field(proto.MESSAGE, number=7, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=8, message=timestamp.Timestamp,) + entry_count = proto.Field(proto.INT32, number=6,) + submit_time = proto.Field(proto.MESSAGE, number=7, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=8, message=timestamp_pb2.Timestamp,) class CreateGlossaryRequest(proto.Message): r"""Request message for CreateGlossary. - Attributes: parent (str): Required. The project name. @@ -1139,37 +1052,33 @@ class CreateGlossaryRequest(proto.Message): Required. The glossary to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) glossary = proto.Field(proto.MESSAGE, number=2, message="Glossary",) class GetGlossaryRequest(proto.Message): r"""Request message for GetGlossary. - Attributes: name (str): Required. The name of the glossary to retrieve. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class DeleteGlossaryRequest(proto.Message): r"""Request message for DeleteGlossary. - Attributes: name (str): Required. The name of the glossary to delete. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListGlossariesRequest(proto.Message): r"""Request message for ListGlossaries. - Attributes: parent (str): Required. The name of the project from which @@ -1212,18 +1121,14 @@ class ListGlossariesRequest(proto.Message): performed. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - filter = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + filter = proto.Field(proto.STRING, number=4,) class ListGlossariesResponse(proto.Message): r"""Response message for ListGlossaries. - Attributes: glossaries (Sequence[google.cloud.translate_v3beta1.types.Glossary]): The list of glossaries for a project. @@ -1239,8 +1144,7 @@ def raw_page(self): return self glossaries = proto.RepeatedField(proto.MESSAGE, number=1, message="Glossary",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class CreateGlossaryMetadata(proto.Message): @@ -1271,11 +1175,9 @@ class State(proto.Enum): CANCELLING = 4 CANCELLED = 5 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) state = proto.Field(proto.ENUM, number=2, enum=State,) - - submit_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + submit_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) class DeleteGlossaryMetadata(proto.Message): @@ -1306,11 +1208,9 @@ class State(proto.Enum): CANCELLING = 4 CANCELLED = 5 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) state = proto.Field(proto.ENUM, number=2, enum=State,) - - submit_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + submit_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) class DeleteGlossaryResponse(proto.Message): @@ -1330,16 +1230,13 @@ class DeleteGlossaryResponse(proto.Message): is set to true. """ - name = proto.Field(proto.STRING, number=1) - - submit_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + name = proto.Field(proto.STRING, number=1,) + submit_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) class BatchTranslateDocumentRequest(proto.Message): r"""The BatchTranslateDocument request. - Attributes: parent (str): Required. Location to make a regional call. @@ -1396,22 +1293,16 @@ class BatchTranslateDocumentRequest(proto.Message): keyed by target language code. """ - parent = proto.Field(proto.STRING, number=1) - - source_language_code = proto.Field(proto.STRING, number=2) - - target_language_codes = proto.RepeatedField(proto.STRING, number=3) - + parent = proto.Field(proto.STRING, number=1,) + source_language_code = proto.Field(proto.STRING, number=2,) + target_language_codes = proto.RepeatedField(proto.STRING, number=3,) input_configs = proto.RepeatedField( proto.MESSAGE, number=4, message="BatchDocumentInputConfig", ) - output_config = proto.Field( proto.MESSAGE, number=5, message="BatchDocumentOutputConfig", ) - - models = proto.MapField(proto.STRING, proto.STRING, number=6) - + models = proto.MapField(proto.STRING, proto.STRING, number=6,) glossaries = proto.MapField( proto.STRING, proto.MESSAGE, number=7, message="TranslateTextGlossaryConfig", ) @@ -1419,7 +1310,6 @@ class BatchTranslateDocumentRequest(proto.Message): class BatchDocumentInputConfig(proto.Message): r"""Input configuration for BatchTranslateDocument request. - Attributes: gcs_source (google.cloud.translate_v3beta1.types.GcsSource): Google Cloud Storage location for the source input. This can @@ -1451,7 +1341,6 @@ class BatchDocumentInputConfig(proto.Message): class BatchDocumentOutputConfig(proto.Message): r"""Output configuration for BatchTranslateDocument request. - Attributes: gcs_destination (google.cloud.translate_v3beta1.types.GcsDestination): Google Cloud Storage destination for output content. For @@ -1556,30 +1445,20 @@ class BatchTranslateDocumentResponse(proto.Message): is set to true. """ - total_pages = proto.Field(proto.INT64, number=1) - - translated_pages = proto.Field(proto.INT64, number=2) - - failed_pages = proto.Field(proto.INT64, number=3) - - total_billable_pages = proto.Field(proto.INT64, number=4) - - total_characters = proto.Field(proto.INT64, number=5) - - translated_characters = proto.Field(proto.INT64, number=6) - - failed_characters = proto.Field(proto.INT64, number=7) - - total_billable_characters = proto.Field(proto.INT64, number=8) - - submit_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) + total_pages = proto.Field(proto.INT64, number=1,) + translated_pages = proto.Field(proto.INT64, number=2,) + failed_pages = proto.Field(proto.INT64, number=3,) + total_billable_pages = proto.Field(proto.INT64, number=4,) + total_characters = proto.Field(proto.INT64, number=5,) + translated_characters = proto.Field(proto.INT64, number=6,) + failed_characters = proto.Field(proto.INT64, number=7,) + total_billable_characters = proto.Field(proto.INT64, number=8,) + submit_time = proto.Field(proto.MESSAGE, number=9, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=10, message=timestamp_pb2.Timestamp,) class BatchTranslateDocumentMetadata(proto.Message): r"""State metadata for the batch translation operation. - Attributes: state (google.cloud.translate_v3beta1.types.BatchTranslateDocumentMetadata.State): The state of the operation. @@ -1627,24 +1506,17 @@ class State(proto.Enum): CANCELLED = 5 state = proto.Field(proto.ENUM, number=1, enum=State,) - - total_pages = proto.Field(proto.INT64, number=2) - - translated_pages = proto.Field(proto.INT64, number=3) - - failed_pages = proto.Field(proto.INT64, number=4) - - total_billable_pages = proto.Field(proto.INT64, number=5) - - total_characters = proto.Field(proto.INT64, number=6) - - translated_characters = proto.Field(proto.INT64, number=7) - - failed_characters = proto.Field(proto.INT64, number=8) - - total_billable_characters = proto.Field(proto.INT64, number=9) - - submit_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) + total_pages = proto.Field(proto.INT64, number=2,) + translated_pages = proto.Field(proto.INT64, number=3,) + failed_pages = proto.Field(proto.INT64, number=4,) + total_billable_pages = proto.Field(proto.INT64, number=5,) + total_characters = proto.Field(proto.INT64, number=6,) + translated_characters = proto.Field(proto.INT64, number=7,) + failed_characters = proto.Field(proto.INT64, number=8,) + total_billable_characters = proto.Field(proto.INT64, number=9,) + submit_time = proto.Field( + proto.MESSAGE, number=10, message=timestamp_pb2.Timestamp, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/scripts/fixup_translate_v3_keywords.py b/scripts/fixup_translate_v3_keywords.py index 7bf59c96..415e7790 100644 --- a/scripts/fixup_translate_v3_keywords.py +++ b/scripts/fixup_translate_v3_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,15 +39,14 @@ def partition( class translateCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_translate_text': ('parent', 'source_language_code', 'target_language_codes', 'input_configs', 'output_config', 'models', 'glossaries', 'labels', ), - 'create_glossary': ('parent', 'glossary', ), - 'delete_glossary': ('name', ), - 'detect_language': ('parent', 'model', 'content', 'mime_type', 'labels', ), - 'get_glossary': ('name', ), - 'get_supported_languages': ('parent', 'display_language_code', 'model', ), - 'list_glossaries': ('parent', 'page_size', 'page_token', 'filter', ), - 'translate_text': ('contents', 'target_language_code', 'parent', 'mime_type', 'source_language_code', 'model', 'glossary_config', 'labels', ), - + 'batch_translate_text': ('parent', 'source_language_code', 'target_language_codes', 'input_configs', 'output_config', 'models', 'glossaries', 'labels', ), + 'create_glossary': ('parent', 'glossary', ), + 'delete_glossary': ('name', ), + 'detect_language': ('parent', 'model', 'content', 'mime_type', 'labels', ), + 'get_glossary': ('name', ), + 'get_supported_languages': ('parent', 'display_language_code', 'model', ), + 'list_glossaries': ('parent', 'page_size', 'page_token', 'filter', ), + 'translate_text': ('contents', 'target_language_code', 'parent', 'mime_type', 'source_language_code', 'model', 'glossary_config', 'labels', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -80,7 +77,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/scripts/fixup_translate_v3beta1_keywords.py b/scripts/fixup_translate_v3beta1_keywords.py index 6df60492..0db3d03e 100644 --- a/scripts/fixup_translate_v3beta1_keywords.py +++ b/scripts/fixup_translate_v3beta1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,17 +39,16 @@ 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', ), - 'batch_translate_text': ('parent', 'source_language_code', 'target_language_codes', 'input_configs', 'output_config', 'models', 'glossaries', 'labels', ), - 'create_glossary': ('parent', 'glossary', ), - 'delete_glossary': ('name', ), - 'detect_language': ('parent', 'model', 'content', 'mime_type', 'labels', ), - '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_text': ('contents', 'target_language_code', 'parent', 'mime_type', 'source_language_code', 'model', 'glossary_config', 'labels', ), - + 'batch_translate_document': ('parent', 'source_language_code', 'target_language_codes', 'input_configs', 'output_config', 'models', 'glossaries', ), + 'batch_translate_text': ('parent', 'source_language_code', 'target_language_codes', 'input_configs', 'output_config', 'models', 'glossaries', 'labels', ), + 'create_glossary': ('parent', 'glossary', ), + 'delete_glossary': ('name', ), + 'detect_language': ('parent', 'model', 'content', 'mime_type', 'labels', ), + '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_text': ('contents', 'target_language_code', 'parent', 'mime_type', 'source_language_code', 'model', 'glossary_config', 'labels', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -82,7 +79,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/setup.py b/setup.py index d8d11154..df4d8a3b 100644 --- a/setup.py +++ b/setup.py @@ -32,6 +32,7 @@ "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", "google-cloud-core >= 1.3.0, < 2.0dev", "proto-plus >= 0.4.0", + "packaging >= 14.3", ] extras = {} diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index d698348c..6bb2a8b3 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -8,3 +8,5 @@ google-api-core==1.22.2 google-cloud-core==1.3.0 proto-plus==0.4.0 +packaging==14.3 +google-auth==1.24.0 # TODO: remove when google-auth>=1.25.0 is transitively required through google-api-core diff --git a/tests/__init__.py b/tests/__init__.py index e69de29b..4de65971 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 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. +# diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 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. +# diff --git a/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/tests/unit/gapic/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 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. +# diff --git a/tests/unit/gapic/translate_v3/__init__.py b/tests/unit/gapic/translate_v3/__init__.py index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/translate_v3/__init__.py +++ b/tests/unit/gapic/translate_v3/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/translate_v3/test_translation_service.py b/tests/unit/gapic/translate_v3/test_translation_service.py index 6950ea3c..8ef34c45 100644 --- a/tests/unit/gapic/translate_v3/test_translation_service.py +++ b/tests/unit/gapic/translate_v3/test_translation_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,16 +23,16 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.translate_v3.services.translation_service import ( TranslationServiceAsyncClient, @@ -43,10 +42,40 @@ ) from google.cloud.translate_v3.services.translation_service import pagers from google.cloud.translate_v3.services.translation_service import transports +from google.cloud.translate_v3.services.translation_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.translate_v3.services.translation_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.translate_v3.types import translation_service from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -98,7 +127,7 @@ def test__get_default_mtls_endpoint(): "client_class", [TranslationServiceClient, TranslationServiceAsyncClient,] ) def test_translation_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -115,7 +144,7 @@ def test_translation_service_client_from_service_account_info(client_class): "client_class", [TranslationServiceClient, TranslationServiceAsyncClient,] ) def test_translation_service_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -168,7 +197,7 @@ def test_translation_service_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(TranslationServiceClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -466,7 +495,7 @@ def test_translate_text( transport: str = "grpc", request_type=translation_service.TranslateTextRequest ): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -477,17 +506,14 @@ def test_translate_text( with mock.patch.object(type(client.transport.translate_text), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = translation_service.TranslateTextResponse() - response = client.translate_text(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.TranslateTextRequest() # Establish that the response is the type that we expect. - assert isinstance(response, translation_service.TranslateTextResponse) @@ -499,7 +525,7 @@ def test_translate_text_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -507,7 +533,6 @@ def test_translate_text_empty_call(): client.translate_text() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.TranslateTextRequest() @@ -517,7 +542,7 @@ async def test_translate_text_async( request_type=translation_service.TranslateTextRequest, ): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -530,13 +555,11 @@ async def test_translate_text_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.TranslateTextResponse() ) - response = await client.translate_text(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.TranslateTextRequest() # Establish that the response is the type that we expect. @@ -549,17 +572,19 @@ async def test_translate_text_async_from_dict(): def test_translate_text_field_headers(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.TranslateTextRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.translate_text), "__call__") as call: call.return_value = translation_service.TranslateTextResponse() - client.translate_text(request) # Establish that the underlying gRPC stub method was called. @@ -575,12 +600,13 @@ def test_translate_text_field_headers(): @pytest.mark.asyncio async def test_translate_text_field_headers_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.TranslateTextRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -588,7 +614,6 @@ async def test_translate_text_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.TranslateTextResponse() ) - await client.translate_text(request) # Establish that the underlying gRPC stub method was called. @@ -602,13 +627,14 @@ async def test_translate_text_field_headers_async(): def test_translate_text_flattened(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.translate_text), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = translation_service.TranslateTextResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.translate_text( @@ -624,22 +650,18 @@ def test_translate_text_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].target_language_code == "target_language_code_value" - assert args[0].contents == ["contents_value"] - assert args[0].model == "model_value" - assert args[0].mime_type == "mime_type_value" - assert args[0].source_language_code == "source_language_code_value" def test_translate_text_flattened_error(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -658,7 +680,7 @@ def test_translate_text_flattened_error(): @pytest.mark.asyncio async def test_translate_text_flattened_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -684,24 +706,18 @@ async def test_translate_text_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].target_language_code == "target_language_code_value" - assert args[0].contents == ["contents_value"] - assert args[0].model == "model_value" - assert args[0].mime_type == "mime_type_value" - assert args[0].source_language_code == "source_language_code_value" @pytest.mark.asyncio async def test_translate_text_flattened_error_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -722,7 +738,7 @@ def test_detect_language( transport: str = "grpc", request_type=translation_service.DetectLanguageRequest ): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -733,17 +749,14 @@ def test_detect_language( with mock.patch.object(type(client.transport.detect_language), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = translation_service.DetectLanguageResponse() - response = client.detect_language(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.DetectLanguageRequest() # Establish that the response is the type that we expect. - assert isinstance(response, translation_service.DetectLanguageResponse) @@ -755,7 +768,7 @@ def test_detect_language_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -763,7 +776,6 @@ def test_detect_language_empty_call(): client.detect_language() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.DetectLanguageRequest() @@ -773,7 +785,7 @@ async def test_detect_language_async( request_type=translation_service.DetectLanguageRequest, ): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -786,13 +798,11 @@ async def test_detect_language_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.DetectLanguageResponse() ) - response = await client.detect_language(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.DetectLanguageRequest() # Establish that the response is the type that we expect. @@ -805,17 +815,19 @@ async def test_detect_language_async_from_dict(): def test_detect_language_field_headers(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.DetectLanguageRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.detect_language), "__call__") as call: call.return_value = translation_service.DetectLanguageResponse() - client.detect_language(request) # Establish that the underlying gRPC stub method was called. @@ -831,12 +843,13 @@ def test_detect_language_field_headers(): @pytest.mark.asyncio async def test_detect_language_field_headers_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.DetectLanguageRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -844,7 +857,6 @@ async def test_detect_language_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.DetectLanguageResponse() ) - await client.detect_language(request) # Establish that the underlying gRPC stub method was called. @@ -858,13 +870,14 @@ async def test_detect_language_field_headers_async(): def test_detect_language_flattened(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.detect_language), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = translation_service.DetectLanguageResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.detect_language( @@ -878,18 +891,16 @@ def test_detect_language_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].model == "model_value" - assert args[0].mime_type == "mime_type_value" - assert args[0].content == "content_value" def test_detect_language_flattened_error(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -906,7 +917,7 @@ def test_detect_language_flattened_error(): @pytest.mark.asyncio async def test_detect_language_flattened_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -930,20 +941,16 @@ async def test_detect_language_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].model == "model_value" - assert args[0].mime_type == "mime_type_value" - assert args[0].content == "content_value" @pytest.mark.asyncio async def test_detect_language_flattened_error_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -963,7 +970,7 @@ def test_get_supported_languages( request_type=translation_service.GetSupportedLanguagesRequest, ): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -976,17 +983,14 @@ def test_get_supported_languages( ) as call: # Designate an appropriate return value for the call. call.return_value = translation_service.SupportedLanguages() - response = client.get_supported_languages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.GetSupportedLanguagesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, translation_service.SupportedLanguages) @@ -998,7 +1002,7 @@ def test_get_supported_languages_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1008,7 +1012,6 @@ def test_get_supported_languages_empty_call(): client.get_supported_languages() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.GetSupportedLanguagesRequest() @@ -1018,7 +1021,7 @@ async def test_get_supported_languages_async( request_type=translation_service.GetSupportedLanguagesRequest, ): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1033,13 +1036,11 @@ async def test_get_supported_languages_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.SupportedLanguages() ) - response = await client.get_supported_languages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.GetSupportedLanguagesRequest() # Establish that the response is the type that we expect. @@ -1052,11 +1053,14 @@ async def test_get_supported_languages_async_from_dict(): def test_get_supported_languages_field_headers(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.GetSupportedLanguagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1064,7 +1068,6 @@ def test_get_supported_languages_field_headers(): type(client.transport.get_supported_languages), "__call__" ) as call: call.return_value = translation_service.SupportedLanguages() - client.get_supported_languages(request) # Establish that the underlying gRPC stub method was called. @@ -1080,12 +1083,13 @@ def test_get_supported_languages_field_headers(): @pytest.mark.asyncio async def test_get_supported_languages_field_headers_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.GetSupportedLanguagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1095,7 +1099,6 @@ async def test_get_supported_languages_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.SupportedLanguages() ) - await client.get_supported_languages(request) # Establish that the underlying gRPC stub method was called. @@ -1109,7 +1112,9 @@ async def test_get_supported_languages_field_headers_async(): def test_get_supported_languages_flattened(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1117,7 +1122,6 @@ def test_get_supported_languages_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = translation_service.SupportedLanguages() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_supported_languages( @@ -1130,16 +1134,15 @@ def test_get_supported_languages_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].model == "model_value" - assert args[0].display_language_code == "display_language_code_value" def test_get_supported_languages_flattened_error(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1155,7 +1158,7 @@ def test_get_supported_languages_flattened_error(): @pytest.mark.asyncio async def test_get_supported_languages_flattened_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1180,18 +1183,15 @@ async def test_get_supported_languages_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].model == "model_value" - assert args[0].display_language_code == "display_language_code_value" @pytest.mark.asyncio async def test_get_supported_languages_flattened_error_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1209,7 +1209,7 @@ def test_batch_translate_text( transport: str = "grpc", request_type=translation_service.BatchTranslateTextRequest ): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1222,13 +1222,11 @@ def test_batch_translate_text( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_translate_text(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.BatchTranslateTextRequest() # Establish that the response is the type that we expect. @@ -1243,7 +1241,7 @@ def test_batch_translate_text_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1253,7 +1251,6 @@ def test_batch_translate_text_empty_call(): client.batch_translate_text() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.BatchTranslateTextRequest() @@ -1263,7 +1260,7 @@ async def test_batch_translate_text_async( request_type=translation_service.BatchTranslateTextRequest, ): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1278,13 +1275,11 @@ async def test_batch_translate_text_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_translate_text(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.BatchTranslateTextRequest() # Establish that the response is the type that we expect. @@ -1297,11 +1292,14 @@ async def test_batch_translate_text_async_from_dict(): def test_batch_translate_text_field_headers(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.BatchTranslateTextRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1309,7 +1307,6 @@ def test_batch_translate_text_field_headers(): type(client.transport.batch_translate_text), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_translate_text(request) # Establish that the underlying gRPC stub method was called. @@ -1325,12 +1322,13 @@ def test_batch_translate_text_field_headers(): @pytest.mark.asyncio async def test_batch_translate_text_field_headers_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.BatchTranslateTextRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1340,7 +1338,6 @@ async def test_batch_translate_text_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_translate_text(request) # Establish that the underlying gRPC stub method was called. @@ -1357,7 +1354,7 @@ def test_create_glossary( transport: str = "grpc", request_type=translation_service.CreateGlossaryRequest ): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1368,13 +1365,11 @@ def test_create_glossary( with mock.patch.object(type(client.transport.create_glossary), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_glossary(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.CreateGlossaryRequest() # Establish that the response is the type that we expect. @@ -1389,7 +1384,7 @@ def test_create_glossary_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1397,7 +1392,6 @@ def test_create_glossary_empty_call(): client.create_glossary() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.CreateGlossaryRequest() @@ -1407,7 +1401,7 @@ async def test_create_glossary_async( request_type=translation_service.CreateGlossaryRequest, ): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1420,13 +1414,11 @@ async def test_create_glossary_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_glossary(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.CreateGlossaryRequest() # Establish that the response is the type that we expect. @@ -1439,17 +1431,19 @@ async def test_create_glossary_async_from_dict(): def test_create_glossary_field_headers(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.CreateGlossaryRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_glossary), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_glossary(request) # Establish that the underlying gRPC stub method was called. @@ -1465,12 +1459,13 @@ def test_create_glossary_field_headers(): @pytest.mark.asyncio async def test_create_glossary_field_headers_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.CreateGlossaryRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1478,7 +1473,6 @@ async def test_create_glossary_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_glossary(request) # Establish that the underlying gRPC stub method was called. @@ -1492,13 +1486,14 @@ async def test_create_glossary_field_headers_async(): def test_create_glossary_flattened(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_glossary), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_glossary( @@ -1510,14 +1505,14 @@ def test_create_glossary_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].glossary == translation_service.Glossary(name="name_value") def test_create_glossary_flattened_error(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1532,7 +1527,7 @@ def test_create_glossary_flattened_error(): @pytest.mark.asyncio async def test_create_glossary_flattened_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1554,16 +1549,14 @@ async def test_create_glossary_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].glossary == translation_service.Glossary(name="name_value") @pytest.mark.asyncio async def test_create_glossary_flattened_error_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1580,7 +1573,7 @@ def test_list_glossaries( transport: str = "grpc", request_type=translation_service.ListGlossariesRequest ): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1593,19 +1586,15 @@ def test_list_glossaries( call.return_value = translation_service.ListGlossariesResponse( next_page_token="next_page_token_value", ) - response = client.list_glossaries(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.ListGlossariesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListGlossariesPager) - assert response.next_page_token == "next_page_token_value" @@ -1617,7 +1606,7 @@ def test_list_glossaries_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1625,7 +1614,6 @@ def test_list_glossaries_empty_call(): client.list_glossaries() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.ListGlossariesRequest() @@ -1635,7 +1623,7 @@ async def test_list_glossaries_async( request_type=translation_service.ListGlossariesRequest, ): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1650,18 +1638,15 @@ async def test_list_glossaries_async( next_page_token="next_page_token_value", ) ) - response = await client.list_glossaries(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.ListGlossariesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListGlossariesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1671,17 +1656,19 @@ async def test_list_glossaries_async_from_dict(): def test_list_glossaries_field_headers(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.ListGlossariesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_glossaries), "__call__") as call: call.return_value = translation_service.ListGlossariesResponse() - client.list_glossaries(request) # Establish that the underlying gRPC stub method was called. @@ -1697,12 +1684,13 @@ def test_list_glossaries_field_headers(): @pytest.mark.asyncio async def test_list_glossaries_field_headers_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.ListGlossariesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1710,7 +1698,6 @@ async def test_list_glossaries_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.ListGlossariesResponse() ) - await client.list_glossaries(request) # Establish that the underlying gRPC stub method was called. @@ -1724,13 +1711,14 @@ async def test_list_glossaries_field_headers_async(): def test_list_glossaries_flattened(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_glossaries), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = translation_service.ListGlossariesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_glossaries(parent="parent_value",) @@ -1739,12 +1727,13 @@ def test_list_glossaries_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_glossaries_flattened_error(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1757,7 +1746,7 @@ def test_list_glossaries_flattened_error(): @pytest.mark.asyncio async def test_list_glossaries_flattened_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1776,14 +1765,13 @@ async def test_list_glossaries_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_glossaries_flattened_error_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1795,7 +1783,7 @@ async def test_list_glossaries_flattened_error_async(): def test_list_glossaries_pager(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials,) + client = TranslationServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_glossaries), "__call__") as call: @@ -1838,7 +1826,7 @@ def test_list_glossaries_pager(): def test_list_glossaries_pages(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials,) + client = TranslationServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_glossaries), "__call__") as call: @@ -1874,7 +1862,7 @@ def test_list_glossaries_pages(): @pytest.mark.asyncio async def test_list_glossaries_async_pager(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1918,7 +1906,7 @@ async def test_list_glossaries_async_pager(): @pytest.mark.asyncio async def test_list_glossaries_async_pages(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1960,7 +1948,7 @@ def test_get_glossary( transport: str = "grpc", request_type=translation_service.GetGlossaryRequest ): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1977,21 +1965,16 @@ def test_get_glossary( source_language_code="source_language_code_value" ), ) - response = client.get_glossary(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.GetGlossaryRequest() # 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 @@ -2003,7 +1986,7 @@ def test_get_glossary_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2011,7 +1994,6 @@ def test_get_glossary_empty_call(): client.get_glossary() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.GetGlossaryRequest() @@ -2020,7 +2002,7 @@ async def test_get_glossary_async( transport: str = "grpc_asyncio", request_type=translation_service.GetGlossaryRequest ): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2033,20 +2015,16 @@ async def test_get_glossary_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.Glossary(name="name_value", entry_count=1210,) ) - response = await client.get_glossary(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.GetGlossaryRequest() # 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 @@ -2056,17 +2034,19 @@ async def test_get_glossary_async_from_dict(): def test_get_glossary_field_headers(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.GetGlossaryRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_glossary), "__call__") as call: call.return_value = translation_service.Glossary() - client.get_glossary(request) # Establish that the underlying gRPC stub method was called. @@ -2082,12 +2062,13 @@ def test_get_glossary_field_headers(): @pytest.mark.asyncio async def test_get_glossary_field_headers_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.GetGlossaryRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2095,7 +2076,6 @@ async def test_get_glossary_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.Glossary() ) - await client.get_glossary(request) # Establish that the underlying gRPC stub method was called. @@ -2109,13 +2089,14 @@ async def test_get_glossary_field_headers_async(): def test_get_glossary_flattened(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_glossary), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = translation_service.Glossary() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_glossary(name="name_value",) @@ -2124,12 +2105,13 @@ def test_get_glossary_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_glossary_flattened_error(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2142,7 +2124,7 @@ def test_get_glossary_flattened_error(): @pytest.mark.asyncio async def test_get_glossary_flattened_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2161,14 +2143,13 @@ async def test_get_glossary_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_glossary_flattened_error_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2183,7 +2164,7 @@ def test_delete_glossary( transport: str = "grpc", request_type=translation_service.DeleteGlossaryRequest ): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2194,13 +2175,11 @@ def test_delete_glossary( with mock.patch.object(type(client.transport.delete_glossary), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_glossary(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.DeleteGlossaryRequest() # Establish that the response is the type that we expect. @@ -2215,7 +2194,7 @@ def test_delete_glossary_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2223,7 +2202,6 @@ def test_delete_glossary_empty_call(): client.delete_glossary() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.DeleteGlossaryRequest() @@ -2233,7 +2211,7 @@ async def test_delete_glossary_async( request_type=translation_service.DeleteGlossaryRequest, ): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2246,13 +2224,11 @@ async def test_delete_glossary_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.delete_glossary(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.DeleteGlossaryRequest() # Establish that the response is the type that we expect. @@ -2265,17 +2241,19 @@ async def test_delete_glossary_async_from_dict(): def test_delete_glossary_field_headers(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.DeleteGlossaryRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_glossary), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_glossary(request) # Establish that the underlying gRPC stub method was called. @@ -2291,12 +2269,13 @@ def test_delete_glossary_field_headers(): @pytest.mark.asyncio async def test_delete_glossary_field_headers_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.DeleteGlossaryRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2304,7 +2283,6 @@ async def test_delete_glossary_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.delete_glossary(request) # Establish that the underlying gRPC stub method was called. @@ -2318,13 +2296,14 @@ async def test_delete_glossary_field_headers_async(): def test_delete_glossary_flattened(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_glossary), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_glossary(name="name_value",) @@ -2333,12 +2312,13 @@ def test_delete_glossary_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_glossary_flattened_error(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2351,7 +2331,7 @@ def test_delete_glossary_flattened_error(): @pytest.mark.asyncio async def test_delete_glossary_flattened_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2370,14 +2350,13 @@ async def test_delete_glossary_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_glossary_flattened_error_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2391,16 +2370,16 @@ 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( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.TranslationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TranslationServiceClient( @@ -2410,7 +2389,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.TranslationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TranslationServiceClient( @@ -2421,7 +2400,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.TranslationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = TranslationServiceClient(transport=transport) assert client.transport is transport @@ -2430,13 +2409,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.TranslationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.TranslationServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2451,23 +2430,25 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + 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(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.TranslationServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2479,7 +2460,7 @@ def test_translation_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.TranslationServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2504,15 +2485,40 @@ def test_translation_service_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_translation_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.translate_v3.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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_translation_service_base_transport_with_credentials_file_old_google_auth(): + # 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_v3.services.translation_service.transports.TranslationServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TranslationServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2528,19 +2534,36 @@ def test_translation_service_base_transport_with_credentials_file(): 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(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.translate_v3.services.translation_service.transports.TranslationServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TranslationServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_translation_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_translation_service_auth_adc_old_google_auth(): + # 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=( @@ -2551,14 +2574,44 @@ def test_translation_service_auth_adc(): ) -def test_translation_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.TranslationServiceGrpcTransport, + transports.TranslationServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_translation_service_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.TranslationServiceGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TranslationServiceGrpcTransport, + transports.TranslationServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_translation_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -2568,6 +2621,121 @@ def test_translation_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TranslationServiceGrpcTransport, grpc_helpers), + (transports.TranslationServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_translation_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "translate.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + scopes=["1", "2"], + default_host="translate.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TranslationServiceGrpcTransport, grpc_helpers), + (transports.TranslationServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_translation_service_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "translate.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TranslationServiceGrpcTransport, grpc_helpers), + (transports.TranslationServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_translation_service_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "translate.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2578,7 +2746,7 @@ def test_translation_service_transport_auth_adc(): def test_translation_service_grpc_transport_client_cert_source_for_mtls( transport_class, ): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2620,7 +2788,7 @@ def test_translation_service_grpc_transport_client_cert_source_for_mtls( def test_translation_service_host_no_port(): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="translate.googleapis.com" ), @@ -2630,7 +2798,7 @@ def test_translation_service_host_no_port(): def test_translation_service_host_with_port(): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="translate.googleapis.com:8000" ), @@ -2686,9 +2854,9 @@ def test_translation_service_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2770,7 +2938,7 @@ def test_translation_service_transport_channel_mtls_with_adc(transport_class): def test_translation_service_grpc_lro_client(): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2783,7 +2951,7 @@ def test_translation_service_grpc_lro_client(): def test_translation_service_grpc_lro_async_client(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2798,7 +2966,6 @@ def test_glossary_path(): project = "squid" location = "clam" glossary = "whelk" - expected = "projects/{project}/locations/{location}/glossaries/{glossary}".format( project=project, location=location, glossary=glossary, ) @@ -2821,7 +2988,6 @@ def test_parse_glossary_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2842,7 +3008,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = TranslationServiceClient.common_folder_path(folder) assert expected == actual @@ -2861,7 +3026,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = TranslationServiceClient.common_organization_path(organization) assert expected == actual @@ -2880,7 +3044,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = TranslationServiceClient.common_project_path(project) assert expected == actual @@ -2900,7 +3063,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "whelk" location = "octopus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2927,7 +3089,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.TranslationServiceTransport, "_prep_wrapped_messages" ) as prep: client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2936,6 +3098,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = TranslationServiceClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/translate_v3beta1/__init__.py b/tests/unit/gapic/translate_v3beta1/__init__.py index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/translate_v3beta1/__init__.py +++ b/tests/unit/gapic/translate_v3beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/translate_v3beta1/test_translation_service.py b/tests/unit/gapic/translate_v3beta1/test_translation_service.py index 15060d0e..053c5a74 100644 --- a/tests/unit/gapic/translate_v3beta1/test_translation_service.py +++ b/tests/unit/gapic/translate_v3beta1/test_translation_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,16 +23,16 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.translate_v3beta1.services.translation_service import ( TranslationServiceAsyncClient, @@ -43,10 +42,40 @@ ) from google.cloud.translate_v3beta1.services.translation_service import pagers from google.cloud.translate_v3beta1.services.translation_service import transports +from google.cloud.translate_v3beta1.services.translation_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.translate_v3beta1.services.translation_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.translate_v3beta1.types import translation_service from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -98,7 +127,7 @@ def test__get_default_mtls_endpoint(): "client_class", [TranslationServiceClient, TranslationServiceAsyncClient,] ) def test_translation_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -115,7 +144,7 @@ def test_translation_service_client_from_service_account_info(client_class): "client_class", [TranslationServiceClient, TranslationServiceAsyncClient,] ) def test_translation_service_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -168,7 +197,7 @@ def test_translation_service_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(TranslationServiceClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -466,7 +495,7 @@ def test_translate_text( transport: str = "grpc", request_type=translation_service.TranslateTextRequest ): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -477,17 +506,14 @@ def test_translate_text( with mock.patch.object(type(client.transport.translate_text), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = translation_service.TranslateTextResponse() - response = client.translate_text(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.TranslateTextRequest() # Establish that the response is the type that we expect. - assert isinstance(response, translation_service.TranslateTextResponse) @@ -499,7 +525,7 @@ def test_translate_text_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -507,7 +533,6 @@ def test_translate_text_empty_call(): client.translate_text() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.TranslateTextRequest() @@ -517,7 +542,7 @@ async def test_translate_text_async( request_type=translation_service.TranslateTextRequest, ): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -530,13 +555,11 @@ async def test_translate_text_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.TranslateTextResponse() ) - response = await client.translate_text(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.TranslateTextRequest() # Establish that the response is the type that we expect. @@ -549,17 +572,19 @@ async def test_translate_text_async_from_dict(): def test_translate_text_field_headers(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.TranslateTextRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.translate_text), "__call__") as call: call.return_value = translation_service.TranslateTextResponse() - client.translate_text(request) # Establish that the underlying gRPC stub method was called. @@ -575,12 +600,13 @@ def test_translate_text_field_headers(): @pytest.mark.asyncio async def test_translate_text_field_headers_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.TranslateTextRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -588,7 +614,6 @@ async def test_translate_text_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.TranslateTextResponse() ) - await client.translate_text(request) # Establish that the underlying gRPC stub method was called. @@ -605,7 +630,7 @@ def test_detect_language( transport: str = "grpc", request_type=translation_service.DetectLanguageRequest ): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -616,17 +641,14 @@ def test_detect_language( with mock.patch.object(type(client.transport.detect_language), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = translation_service.DetectLanguageResponse() - response = client.detect_language(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.DetectLanguageRequest() # Establish that the response is the type that we expect. - assert isinstance(response, translation_service.DetectLanguageResponse) @@ -638,7 +660,7 @@ def test_detect_language_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -646,7 +668,6 @@ def test_detect_language_empty_call(): client.detect_language() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.DetectLanguageRequest() @@ -656,7 +677,7 @@ async def test_detect_language_async( request_type=translation_service.DetectLanguageRequest, ): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -669,13 +690,11 @@ async def test_detect_language_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.DetectLanguageResponse() ) - response = await client.detect_language(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.DetectLanguageRequest() # Establish that the response is the type that we expect. @@ -688,17 +707,19 @@ async def test_detect_language_async_from_dict(): def test_detect_language_field_headers(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.DetectLanguageRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.detect_language), "__call__") as call: call.return_value = translation_service.DetectLanguageResponse() - client.detect_language(request) # Establish that the underlying gRPC stub method was called. @@ -714,12 +735,13 @@ def test_detect_language_field_headers(): @pytest.mark.asyncio async def test_detect_language_field_headers_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.DetectLanguageRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -727,7 +749,6 @@ async def test_detect_language_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.DetectLanguageResponse() ) - await client.detect_language(request) # Establish that the underlying gRPC stub method was called. @@ -741,13 +762,14 @@ async def test_detect_language_field_headers_async(): def test_detect_language_flattened(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.detect_language), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = translation_service.DetectLanguageResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.detect_language( @@ -758,16 +780,15 @@ def test_detect_language_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].model == "model_value" - assert args[0].mime_type == "mime_type_value" def test_detect_language_flattened_error(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -783,7 +804,7 @@ def test_detect_language_flattened_error(): @pytest.mark.asyncio async def test_detect_language_flattened_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -804,18 +825,15 @@ async def test_detect_language_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].model == "model_value" - assert args[0].mime_type == "mime_type_value" @pytest.mark.asyncio async def test_detect_language_flattened_error_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -834,7 +852,7 @@ def test_get_supported_languages( request_type=translation_service.GetSupportedLanguagesRequest, ): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -847,17 +865,14 @@ def test_get_supported_languages( ) as call: # Designate an appropriate return value for the call. call.return_value = translation_service.SupportedLanguages() - response = client.get_supported_languages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.GetSupportedLanguagesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, translation_service.SupportedLanguages) @@ -869,7 +884,7 @@ def test_get_supported_languages_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -879,7 +894,6 @@ def test_get_supported_languages_empty_call(): client.get_supported_languages() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.GetSupportedLanguagesRequest() @@ -889,7 +903,7 @@ async def test_get_supported_languages_async( request_type=translation_service.GetSupportedLanguagesRequest, ): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -904,13 +918,11 @@ async def test_get_supported_languages_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.SupportedLanguages() ) - response = await client.get_supported_languages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.GetSupportedLanguagesRequest() # Establish that the response is the type that we expect. @@ -923,11 +935,14 @@ async def test_get_supported_languages_async_from_dict(): def test_get_supported_languages_field_headers(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.GetSupportedLanguagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -935,7 +950,6 @@ def test_get_supported_languages_field_headers(): type(client.transport.get_supported_languages), "__call__" ) as call: call.return_value = translation_service.SupportedLanguages() - client.get_supported_languages(request) # Establish that the underlying gRPC stub method was called. @@ -951,12 +965,13 @@ def test_get_supported_languages_field_headers(): @pytest.mark.asyncio async def test_get_supported_languages_field_headers_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.GetSupportedLanguagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -966,7 +981,6 @@ async def test_get_supported_languages_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.SupportedLanguages() ) - await client.get_supported_languages(request) # Establish that the underlying gRPC stub method was called. @@ -980,7 +994,9 @@ async def test_get_supported_languages_field_headers_async(): def test_get_supported_languages_flattened(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -988,7 +1004,6 @@ def test_get_supported_languages_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = translation_service.SupportedLanguages() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_supported_languages( @@ -1001,16 +1016,15 @@ def test_get_supported_languages_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].display_language_code == "display_language_code_value" - assert args[0].model == "model_value" def test_get_supported_languages_flattened_error(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1026,7 +1040,7 @@ def test_get_supported_languages_flattened_error(): @pytest.mark.asyncio async def test_get_supported_languages_flattened_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1051,18 +1065,15 @@ async def test_get_supported_languages_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].display_language_code == "display_language_code_value" - assert args[0].model == "model_value" @pytest.mark.asyncio async def test_get_supported_languages_flattened_error_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1080,7 +1091,7 @@ def test_translate_document( transport: str = "grpc", request_type=translation_service.TranslateDocumentRequest ): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1095,19 +1106,15 @@ def test_translate_document( call.return_value = translation_service.TranslateDocumentResponse( model="model_value", ) - response = client.translate_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.TranslateDocumentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, translation_service.TranslateDocumentResponse) - assert response.model == "model_value" @@ -1119,7 +1126,7 @@ def test_translate_document_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1129,7 +1136,6 @@ def test_translate_document_empty_call(): client.translate_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.TranslateDocumentRequest() @@ -1139,7 +1145,7 @@ async def test_translate_document_async( request_type=translation_service.TranslateDocumentRequest, ): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1154,18 +1160,15 @@ async def test_translate_document_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.TranslateDocumentResponse(model="model_value",) ) - response = await client.translate_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.TranslateDocumentRequest() # Establish that the response is the type that we expect. assert isinstance(response, translation_service.TranslateDocumentResponse) - assert response.model == "model_value" @@ -1175,11 +1178,14 @@ async def test_translate_document_async_from_dict(): def test_translate_document_field_headers(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.TranslateDocumentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1187,7 +1193,6 @@ def test_translate_document_field_headers(): type(client.transport.translate_document), "__call__" ) as call: call.return_value = translation_service.TranslateDocumentResponse() - client.translate_document(request) # Establish that the underlying gRPC stub method was called. @@ -1203,12 +1208,13 @@ def test_translate_document_field_headers(): @pytest.mark.asyncio async def test_translate_document_field_headers_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.TranslateDocumentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1218,7 +1224,6 @@ async def test_translate_document_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.TranslateDocumentResponse() ) - await client.translate_document(request) # Establish that the underlying gRPC stub method was called. @@ -1235,7 +1240,7 @@ def test_batch_translate_text( transport: str = "grpc", request_type=translation_service.BatchTranslateTextRequest ): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1248,13 +1253,11 @@ def test_batch_translate_text( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_translate_text(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.BatchTranslateTextRequest() # Establish that the response is the type that we expect. @@ -1269,7 +1272,7 @@ def test_batch_translate_text_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1279,7 +1282,6 @@ def test_batch_translate_text_empty_call(): client.batch_translate_text() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.BatchTranslateTextRequest() @@ -1289,7 +1291,7 @@ async def test_batch_translate_text_async( request_type=translation_service.BatchTranslateTextRequest, ): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1304,13 +1306,11 @@ async def test_batch_translate_text_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_translate_text(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.BatchTranslateTextRequest() # Establish that the response is the type that we expect. @@ -1323,11 +1323,14 @@ async def test_batch_translate_text_async_from_dict(): def test_batch_translate_text_field_headers(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.BatchTranslateTextRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1335,7 +1338,6 @@ def test_batch_translate_text_field_headers(): type(client.transport.batch_translate_text), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_translate_text(request) # Establish that the underlying gRPC stub method was called. @@ -1351,12 +1353,13 @@ def test_batch_translate_text_field_headers(): @pytest.mark.asyncio async def test_batch_translate_text_field_headers_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.BatchTranslateTextRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1366,7 +1369,6 @@ async def test_batch_translate_text_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_translate_text(request) # Establish that the underlying gRPC stub method was called. @@ -1384,7 +1386,7 @@ def test_batch_translate_document( request_type=translation_service.BatchTranslateDocumentRequest, ): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1397,13 +1399,11 @@ def test_batch_translate_document( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_translate_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.BatchTranslateDocumentRequest() # Establish that the response is the type that we expect. @@ -1418,7 +1418,7 @@ def test_batch_translate_document_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1428,7 +1428,6 @@ def test_batch_translate_document_empty_call(): client.batch_translate_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.BatchTranslateDocumentRequest() @@ -1438,7 +1437,7 @@ async def test_batch_translate_document_async( request_type=translation_service.BatchTranslateDocumentRequest, ): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1453,13 +1452,11 @@ async def test_batch_translate_document_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_translate_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.BatchTranslateDocumentRequest() # Establish that the response is the type that we expect. @@ -1472,11 +1469,14 @@ async def test_batch_translate_document_async_from_dict(): def test_batch_translate_document_field_headers(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.BatchTranslateDocumentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1484,7 +1484,6 @@ def test_batch_translate_document_field_headers(): type(client.transport.batch_translate_document), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_translate_document(request) # Establish that the underlying gRPC stub method was called. @@ -1500,12 +1499,13 @@ def test_batch_translate_document_field_headers(): @pytest.mark.asyncio async def test_batch_translate_document_field_headers_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.BatchTranslateDocumentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1515,7 +1515,6 @@ async def test_batch_translate_document_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_translate_document(request) # Establish that the underlying gRPC stub method was called. @@ -1532,7 +1531,7 @@ def test_create_glossary( transport: str = "grpc", request_type=translation_service.CreateGlossaryRequest ): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1543,13 +1542,11 @@ def test_create_glossary( with mock.patch.object(type(client.transport.create_glossary), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_glossary(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.CreateGlossaryRequest() # Establish that the response is the type that we expect. @@ -1564,7 +1561,7 @@ def test_create_glossary_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1572,7 +1569,6 @@ def test_create_glossary_empty_call(): client.create_glossary() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.CreateGlossaryRequest() @@ -1582,7 +1578,7 @@ async def test_create_glossary_async( request_type=translation_service.CreateGlossaryRequest, ): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1595,13 +1591,11 @@ async def test_create_glossary_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_glossary(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.CreateGlossaryRequest() # Establish that the response is the type that we expect. @@ -1614,17 +1608,19 @@ async def test_create_glossary_async_from_dict(): def test_create_glossary_field_headers(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.CreateGlossaryRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_glossary), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_glossary(request) # Establish that the underlying gRPC stub method was called. @@ -1640,12 +1636,13 @@ def test_create_glossary_field_headers(): @pytest.mark.asyncio async def test_create_glossary_field_headers_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.CreateGlossaryRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1653,7 +1650,6 @@ async def test_create_glossary_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_glossary(request) # Establish that the underlying gRPC stub method was called. @@ -1667,13 +1663,14 @@ async def test_create_glossary_field_headers_async(): def test_create_glossary_flattened(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_glossary), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_glossary( @@ -1685,14 +1682,14 @@ def test_create_glossary_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].glossary == translation_service.Glossary(name="name_value") def test_create_glossary_flattened_error(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1707,7 +1704,7 @@ def test_create_glossary_flattened_error(): @pytest.mark.asyncio async def test_create_glossary_flattened_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1729,16 +1726,14 @@ async def test_create_glossary_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].glossary == translation_service.Glossary(name="name_value") @pytest.mark.asyncio async def test_create_glossary_flattened_error_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1755,7 +1750,7 @@ def test_list_glossaries( transport: str = "grpc", request_type=translation_service.ListGlossariesRequest ): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1768,19 +1763,15 @@ def test_list_glossaries( call.return_value = translation_service.ListGlossariesResponse( next_page_token="next_page_token_value", ) - response = client.list_glossaries(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.ListGlossariesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListGlossariesPager) - assert response.next_page_token == "next_page_token_value" @@ -1792,7 +1783,7 @@ def test_list_glossaries_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1800,7 +1791,6 @@ def test_list_glossaries_empty_call(): client.list_glossaries() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.ListGlossariesRequest() @@ -1810,7 +1800,7 @@ async def test_list_glossaries_async( request_type=translation_service.ListGlossariesRequest, ): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1825,18 +1815,15 @@ async def test_list_glossaries_async( next_page_token="next_page_token_value", ) ) - response = await client.list_glossaries(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.ListGlossariesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListGlossariesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1846,17 +1833,19 @@ async def test_list_glossaries_async_from_dict(): def test_list_glossaries_field_headers(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.ListGlossariesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_glossaries), "__call__") as call: call.return_value = translation_service.ListGlossariesResponse() - client.list_glossaries(request) # Establish that the underlying gRPC stub method was called. @@ -1872,12 +1861,13 @@ def test_list_glossaries_field_headers(): @pytest.mark.asyncio async def test_list_glossaries_field_headers_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.ListGlossariesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1885,7 +1875,6 @@ async def test_list_glossaries_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.ListGlossariesResponse() ) - await client.list_glossaries(request) # Establish that the underlying gRPC stub method was called. @@ -1899,13 +1888,14 @@ async def test_list_glossaries_field_headers_async(): def test_list_glossaries_flattened(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_glossaries), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = translation_service.ListGlossariesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_glossaries( @@ -1916,14 +1906,14 @@ def test_list_glossaries_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].filter == "filter_value" def test_list_glossaries_flattened_error(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1938,7 +1928,7 @@ def test_list_glossaries_flattened_error(): @pytest.mark.asyncio async def test_list_glossaries_flattened_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1959,16 +1949,14 @@ async def test_list_glossaries_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].filter == "filter_value" @pytest.mark.asyncio async def test_list_glossaries_flattened_error_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1982,7 +1970,7 @@ async def test_list_glossaries_flattened_error_async(): def test_list_glossaries_pager(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials,) + client = TranslationServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_glossaries), "__call__") as call: @@ -2025,7 +2013,7 @@ def test_list_glossaries_pager(): def test_list_glossaries_pages(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials,) + client = TranslationServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_glossaries), "__call__") as call: @@ -2061,7 +2049,7 @@ def test_list_glossaries_pages(): @pytest.mark.asyncio async def test_list_glossaries_async_pager(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2105,7 +2093,7 @@ async def test_list_glossaries_async_pager(): @pytest.mark.asyncio async def test_list_glossaries_async_pages(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2147,7 +2135,7 @@ def test_get_glossary( transport: str = "grpc", request_type=translation_service.GetGlossaryRequest ): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2164,21 +2152,16 @@ def test_get_glossary( source_language_code="source_language_code_value" ), ) - response = client.get_glossary(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.GetGlossaryRequest() # 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 @@ -2190,7 +2173,7 @@ def test_get_glossary_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2198,7 +2181,6 @@ def test_get_glossary_empty_call(): client.get_glossary() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.GetGlossaryRequest() @@ -2207,7 +2189,7 @@ async def test_get_glossary_async( transport: str = "grpc_asyncio", request_type=translation_service.GetGlossaryRequest ): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2220,20 +2202,16 @@ async def test_get_glossary_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.Glossary(name="name_value", entry_count=1210,) ) - response = await client.get_glossary(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.GetGlossaryRequest() # 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 @@ -2243,17 +2221,19 @@ async def test_get_glossary_async_from_dict(): def test_get_glossary_field_headers(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.GetGlossaryRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_glossary), "__call__") as call: call.return_value = translation_service.Glossary() - client.get_glossary(request) # Establish that the underlying gRPC stub method was called. @@ -2269,12 +2249,13 @@ def test_get_glossary_field_headers(): @pytest.mark.asyncio async def test_get_glossary_field_headers_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.GetGlossaryRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2282,7 +2263,6 @@ async def test_get_glossary_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( translation_service.Glossary() ) - await client.get_glossary(request) # Establish that the underlying gRPC stub method was called. @@ -2296,13 +2276,14 @@ async def test_get_glossary_field_headers_async(): def test_get_glossary_flattened(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_glossary), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = translation_service.Glossary() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_glossary(name="name_value",) @@ -2311,12 +2292,13 @@ def test_get_glossary_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_glossary_flattened_error(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2329,7 +2311,7 @@ def test_get_glossary_flattened_error(): @pytest.mark.asyncio async def test_get_glossary_flattened_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2348,14 +2330,13 @@ async def test_get_glossary_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_glossary_flattened_error_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2370,7 +2351,7 @@ def test_delete_glossary( transport: str = "grpc", request_type=translation_service.DeleteGlossaryRequest ): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2381,13 +2362,11 @@ def test_delete_glossary( with mock.patch.object(type(client.transport.delete_glossary), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_glossary(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.DeleteGlossaryRequest() # Establish that the response is the type that we expect. @@ -2402,7 +2381,7 @@ def test_delete_glossary_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2410,7 +2389,6 @@ def test_delete_glossary_empty_call(): client.delete_glossary() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.DeleteGlossaryRequest() @@ -2420,7 +2398,7 @@ async def test_delete_glossary_async( request_type=translation_service.DeleteGlossaryRequest, ): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2433,13 +2411,11 @@ async def test_delete_glossary_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.delete_glossary(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == translation_service.DeleteGlossaryRequest() # Establish that the response is the type that we expect. @@ -2452,17 +2428,19 @@ async def test_delete_glossary_async_from_dict(): def test_delete_glossary_field_headers(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.DeleteGlossaryRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_glossary), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_glossary(request) # Establish that the underlying gRPC stub method was called. @@ -2478,12 +2456,13 @@ def test_delete_glossary_field_headers(): @pytest.mark.asyncio async def test_delete_glossary_field_headers_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = translation_service.DeleteGlossaryRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2491,7 +2470,6 @@ async def test_delete_glossary_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.delete_glossary(request) # Establish that the underlying gRPC stub method was called. @@ -2505,13 +2483,14 @@ async def test_delete_glossary_field_headers_async(): def test_delete_glossary_flattened(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_glossary), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_glossary(name="name_value",) @@ -2520,12 +2499,13 @@ def test_delete_glossary_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_glossary_flattened_error(): - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + client = TranslationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2538,7 +2518,7 @@ def test_delete_glossary_flattened_error(): @pytest.mark.asyncio async def test_delete_glossary_flattened_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2557,14 +2537,13 @@ async def test_delete_glossary_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_glossary_flattened_error_async(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2578,16 +2557,16 @@ 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( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.TranslationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TranslationServiceClient( @@ -2597,7 +2576,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.TranslationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TranslationServiceClient( @@ -2608,7 +2587,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.TranslationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = TranslationServiceClient(transport=transport) assert client.transport is transport @@ -2617,13 +2596,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.TranslationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.TranslationServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2638,23 +2617,25 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + 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(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.TranslationServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2666,7 +2647,7 @@ def test_translation_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.TranslationServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2693,15 +2674,40 @@ def test_translation_service_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_translation_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + 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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_translation_service_base_transport_with_credentials_file_old_google_auth(): + # 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 = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TranslationServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2717,19 +2723,36 @@ def test_translation_service_base_transport_with_credentials_file(): 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(auth, "default") as adc, mock.patch( + 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 = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TranslationServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_translation_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_translation_service_auth_adc_old_google_auth(): + # 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=( @@ -2740,14 +2763,44 @@ def test_translation_service_auth_adc(): ) -def test_translation_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.TranslationServiceGrpcTransport, + transports.TranslationServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_translation_service_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.TranslationServiceGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TranslationServiceGrpcTransport, + transports.TranslationServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_translation_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -2757,6 +2810,121 @@ def test_translation_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TranslationServiceGrpcTransport, grpc_helpers), + (transports.TranslationServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_translation_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "translate.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + scopes=["1", "2"], + default_host="translate.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TranslationServiceGrpcTransport, grpc_helpers), + (transports.TranslationServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_translation_service_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "translate.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TranslationServiceGrpcTransport, grpc_helpers), + (transports.TranslationServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_translation_service_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "translate.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2767,7 +2935,7 @@ def test_translation_service_transport_auth_adc(): def test_translation_service_grpc_transport_client_cert_source_for_mtls( transport_class, ): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2809,7 +2977,7 @@ def test_translation_service_grpc_transport_client_cert_source_for_mtls( def test_translation_service_host_no_port(): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="translate.googleapis.com" ), @@ -2819,7 +2987,7 @@ def test_translation_service_host_no_port(): def test_translation_service_host_with_port(): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="translate.googleapis.com:8000" ), @@ -2875,9 +3043,9 @@ def test_translation_service_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2959,7 +3127,7 @@ def test_translation_service_transport_channel_mtls_with_adc(transport_class): def test_translation_service_grpc_lro_client(): client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2972,7 +3140,7 @@ def test_translation_service_grpc_lro_client(): def test_translation_service_grpc_lro_async_client(): client = TranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2987,7 +3155,6 @@ def test_glossary_path(): project = "squid" location = "clam" glossary = "whelk" - expected = "projects/{project}/locations/{location}/glossaries/{glossary}".format( project=project, location=location, glossary=glossary, ) @@ -3010,7 +3177,6 @@ def test_parse_glossary_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3031,7 +3197,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = TranslationServiceClient.common_folder_path(folder) assert expected == actual @@ -3050,7 +3215,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = TranslationServiceClient.common_organization_path(organization) assert expected == actual @@ -3069,7 +3233,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = TranslationServiceClient.common_project_path(project) assert expected == actual @@ -3089,7 +3252,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "whelk" location = "octopus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -3116,7 +3278,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.TranslationServiceTransport, "_prep_wrapped_messages" ) as prep: client = TranslationServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -3125,6 +3287,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = TranslationServiceClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info)